播放器旋转和相机旋转

时间:2018-10-26 18:24:01

标签: c# unity3d

我希望玩家注视方向,相机正在注视。

摄像机跟随玩家(第三人称游戏风格)。

我尝试过

transform.localRotation = new Quaternion(transform.localRotation.x,
  cameraMain.transform.localRotation.y, 
  transform.localRotation.z, 
  transform.localRotation.w);

但它不起作用。

有时候玩家开始向另一个方向旋转。

2 个答案:

答案 0 :(得分:1)

以下代码将使对象(在参数中指定)面向主摄像机所看的方向:

public void lookInDirectionOfCamera(Transform object) {
   RayCastHit hit;
   if (Physics.raycast(cameraMain.transform.position, cameraMain.transform.forward, out hit)) {
      object.forward = hit.point - object.position;
   }else { //if the raycast didnt hit anything, make the object face 100 units in front of the camera
      Vector3 point = Camera.main.transform.position + Camera.main.transform.forward * 100;
      object.forward = point - object.position;
   }
}

这将使播放器面对指向相机的点。如果只希望它们在y轴上具有相同的旋转,请不要使用四元数! 相反,您可以使用欧拉角来做到这一点:

transform.eulerAngles = new Vector3(transform.eulerAngles.x,
cameraMain.transform.eulerAngles.y,
transform.eulerAngles.y);

不使用transform.localRotation的原因是因为这是一个四元数。四元数中的y分量与Euler角中的y轴(您经常看到的)不同,四元数非常令人困惑,因此您几乎不应在其中设置单个值。如果要编辑它们,则仅使用内置方法。

答案 1 :(得分:0)

使用cameraMain.transform.forward获取相机的视向,制作一个y值为零的副本,然后使用Quaternion.SetLookRotation以全局向上的方向朝该方向看。:

Vector3 cameraDirection = cameraMain.transform.forward;
Vector3 characterLookDirection = new Vector3(cameraDirection.x,
                                             0f,
                                             cameraDirection.z);
Quaternion newRotation = new Quaternion();
newRotation.SetLookRotation(characterLookDirection, Vector3.up); 
transform.rotation = newRotation;