Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使我的角色在统一中朝着相机的方向移动_C#_Unity3d - Fatal编程技术网

C# 如何使我的角色在统一中朝着相机的方向移动

C# 如何使我的角色在统一中朝着相机的方向移动,c#,unity3d,C#,Unity3d,我想这样,当我按住w时,它不是朝着一个方向前进,而是朝着我相机所面对的方向前进 我的代码如下 { public CharacterController controller; public float speed = 12f; void Update() { float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 m

我想这样,当我按住w时,它不是朝着一个方向前进,而是朝着我相机所面对的方向前进

我的代码如下

{
   public CharacterController controller;
   public float speed = 12f;

   void Update()
   {
       float x = Input.GetAxis("Horizontal");
       float z = Input.GetAxis("Vertical");

       Vector3 move = transform.right * x + transform.forward * z;

       controller.Move(move * speed * Time.deltaTime);
   }

}

如果是2D游戏,你可以让相机成为玩家的孩子,但当角色旋转时,它会在3D游戏中产生问题。

获取相机的变换,并使用相机变换的右前场,而不是玩家的变换:

Camera mainCam;
public CharacterController controller;
public float speed = 12f;

void Awake()
{
    mainCam = Camera.main; // expensive operation, so cache the results
}


void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = mainCam.transform.right * x + mainCam.transform.forward * z;

    // normalize move if has a magnitude > 1 to prevent faster diagonal movement
    if (move.sqrMagnitude > 1)
    {
        move.Normalize();
    }

    controller.Move(move * speed * Time.deltaTime);
}

这是一款3d游戏,很抱歉应该指定