Unity:如何让相机看一眼

时间:2018-01-16 11:15:23

标签: c# unity3d camera rotation quaternions

我目前正在进行冒险并陷入困境,希望有人可以帮助我: 我希望相机面对一个给定的点,我这样做的方式如下:

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();
    }
}

但问题是它只有在相机旋转0,0,0,1

时才有效

2 个答案:

答案 0 :(得分:1)

 using UnityEngine;
 using System.Collections;

 public class LookAt : MonoBehaviour {
     public Vector3 target;

     // Update is called once per frame
     void Update () {
         transform.LookAt(target);
     }
 }

您只需将此脚本分配给相机即可。 你可以在这里阅读更多相关信息:https://docs.unity3d.com/ScriptReference/Transform.LookAt.html我无法测试代码,但最应该确实有效。

答案 1 :(得分:0)

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);
}