如何在Unity 3d中的第一人称角色控制器中旋转相机

时间:2012-12-24 05:47:06

标签: controller camera rotation character unity3d

我正在开发一款包含第一人称角色控制器的Unity 3D游戏。我试图在它上面旋转主摄像头来模拟角色在他沿着直线行走时左右转动头部。我的问题是我的旋转相机的代码似乎干扰了它所属的角色控制器对象的旋转。

这是我的代码。这个问题似乎发生在最后一行。

void Update () {
    //Send screen image to controller
    StartCoroutine(ScreenshotEncode());

    //the camera is parented to the Character Controller game object.  
    //Dude
    //  +-Capsule
    //  +-MainCamera

    //This code come directly from the Unity script manual
    DudeBase.transform.Rotate(0, Input.GetAxis("Horizontal") * flrBaseMaxRotateSpeed, 0);
    //get the vector the base in pointing toward
    vctBaseDir = DudeBase.transform.TransformDirection(Vector3.forward);
    //get the speed of the base
    fltBaseSpeed = fltBaseMaxSpeed * Input.GetAxis("Vertical");
    //apply speed and direction to the character controller
    controller.SimpleMove(vctBaseDir * fltBaseSpeed);

    //The camera controller comes from the device in degress in the form of a string.
    //get the heading the controller is pointing toward
    fltCamControllerDir = ParseControllerData(strCamControllerData);
    //get the heading of the base
    fltBaseDir = Mathf.Atan2(vctBaseDir.x, vctBaseDir.z);
    //we want to point the camera the angle as the controller.
    //since the camera is sitting on top of and is parented to the base, it needs to offset by the bases heading
    fltCamDir = fltBaseDir + fltCamControllerDir;
    //set the camera's y axis angle
    MainCam.transform.eulerAngles = new Vector3(0, fltCamDir, 0);  // <=== issue seems to be here
    //if i comment out the last line, the character controller moves and rotates as expected.
    //if i uncomment this line, the camera moves on top of the character controller as expected. But,
    //the character controller itself no longer rotates.
}

如何在不影响其父级对象的情况下旋转相机对象?

1 个答案:

答案 0 :(得分:0)

Jerdak的评论是正确答案:

  

向第一个人添加一个新的空子对象并将其称为head. Make the camera a child of head`。

当玩家移动或旋转时,head对象将移动或旋转,使相机随之移动。如果您想独立于身体移动或旋转相机,只需移动/旋转head而不接触身体。