Reputation: 51
im currently working on an adventure and got stuck at this, hopefully someone can help me: I want the camera to face a given point, the way i do it looks like this:
public void LookAtPosition(Vector3 lookPosition, float speed)
{
StartCoroutine(LookAtTransformCorutine(lookPosition, speed));
}
public void LookAtPosition(Transform lookPosition, float speed)
{
LookAtPosition(lookPosition.position, speed);
}
public IEnumerator LookAtTransformCorutine(Vector3 lookPosition, float speed)
{
StopLookingAtMouse();
Vector3 direction = (lookPosition - transform.position).normalized;
Quaternion targetRotation = transform.rotation * Quaternion.FromToRotation(transform.forward, direction);
while (Quaternion.Angle(transform.rotation, targetRotation) > 1f)
{
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, speed);
transform.localRotation = Quaternion.LookRotation(transform.forward);
yield return new WaitForEndOfFrame();
}
}
but the problem is it only works, when the camera has a rotation of 0, 0, 0, 1
Upvotes: 2
Views: 20788
Reputation: 192
public Camera cam; //You cam goes here
public Transform target; //you target goes here
public void LookAtPosition(Transform lookPosition, float speed)
{
cam.transform.LookAt(target);
}
Upvotes: 0
Reputation: 125
using UnityEngine;
using System.Collections;
public class LookAt : MonoBehaviour {
public Vector3 target;
// Update is called once per frame
void Update () {
transform.LookAt(target);
}
}
You just have to assign this script to the camera. You can read more about this here: https://docs.unity3d.com/ScriptReference/Transform.LookAt.html I couldn't test the code but it should most certaintly work.
Upvotes: 4