Lukas Leder
Lukas Leder

Reputation: 51

Unity: How to make camera look at a point

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

Answers (2)

CubeCrafter360
CubeCrafter360

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

Hambalkó Bence
Hambalkó Bence

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

Related Questions