Unity: How to make camera look at a point

12,409
 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.

Share:
12,409
Lukas Leder
Author by

Lukas Leder

Updated on June 05, 2022

Comments

  • Lukas Leder
    Lukas Leder almost 2 years

    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

  • Lukas Leder
    Lukas Leder over 6 years
    This is not what i want, please read the code. LookAt just changes the quaternion in an instand, while i want a smooth lerp with specified speed.
  • otomo
    otomo over 6 years
    You could easily lerp the input vector3 to the lookAt function. Also in your question you asked exactly what Hambalko answered to.
  • CubeCrafter360
    CubeCrafter360 over 6 years
    Im not sure how to add the thingy with time but this should be a help you can work out from
  • CubeCrafter360
    CubeCrafter360 over 6 years
    Ok Cam = the camera in your scene
  • CubeCrafter360
    CubeCrafter360 over 6 years
    transform is the object u want to look ats transform
  • CubeCrafter360
    CubeCrafter360 over 6 years
    cam.transfrom.lookat makes the cam look at the target by turning around