C# 如何使我的角色在统一中朝着相机的方向移动
我想这样,当我按住w时,它不是朝着一个方向前进,而是朝着我相机所面对的方向前进 我的代码如下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
{
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游戏,很抱歉应该指定