C# Unity3D-为什么不';我的球员旋转不正常吗?

C# Unity3D-为什么不';我的球员旋转不正常吗?,c#,unity3d,C#,Unity3d,我正在制作一个自上而下的射手,所以我的相机在我的播放器和地图上方。以下是我在播放器控制器脚本中为移动编写的代码: public class playerMovement : MonoBehaviour { public float speed; private Camera mainCamera; void Start () { mainCamera = FindObjectOfType<Camera>(); } //

我正在制作一个自上而下的射手,所以我的相机在我的播放器和地图上方。以下是我在播放器控制器脚本中为移动编写的代码:

public class playerMovement : MonoBehaviour {

    public float speed;
    private Camera mainCamera;


    void Start () {
        mainCamera = FindObjectOfType<Camera>();
    }

    // Update is called once per frame
    void Update () {

        // player movement
        transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, speed * Input.GetAxis("Vertical") * Time.deltaTime);

        // Camera Ray casting

        Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
        Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
        float rayLength;

        if (groundPlane.Raycast(cameraRay, out rayLength)) {
            Vector3 look = cameraRay.GetPoint(rayLength);
            Debug.DrawLine(cameraRay.origin, look, Color.red);

            transform.LookAt(new Vector3(look.x, transform.position.y, look.z));
        }

    }

}
公共类玩家移动:单一行为{
公众浮标速度;
私人摄像机;
无效开始(){
mainCamera=FindObjectOfType();
}
//每帧调用一次更新
无效更新(){
//球员运动
transform.Translate(速度*Input.GetAxis(“水平”)*Time.deltaTime,0f,速度*Input.GetAxis(“垂直”)*Time.deltaTime);
//相机光线投射
Ray cameraRay=mainCamera.ScreenPointRoay(输入.鼠标位置);
平面接地平面=新平面(矢量3.up,矢量3.zero);
浮动射线长度;
if(地平面光线投射(摄影机阵列,超出光线长度)){
Vector3 look=cameraRay.GetPoint(光线长度);
DrawLine(cameraRay.origin,look,Color.red);
transform.LookAt(新向量3(look.x,transform.position.y,look.z));
}
}
}
我希望能够使用WASD键移动播放器,并按照鼠标所在的方向旋转,但是我不希望播放器的旋转改变键的方向,我需要播放器在按下W键时向前移动,无论播放器朝哪个方向

然而,出于某种原因,我的代码会让玩家根据我不想要的方向向前移动


如何修复此问题?

您需要查看局部坐标系和全局坐标系之间的差异

现在,您的WASD关键点正在根据全局坐标移动玩家角色,您希望WASD的移动取决于玩家的方向,因此需要使用局部坐标系


问题是您的transform.Translate调用位于“self”空间中。向前、向后、左、右都是相对于变换所面对的方向。这就是为什么你的球员是相对于面对的方向移动

如果要相对于“全局”或“世界”空间进行转换,则必须添加一个附加参数

// player movement
transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 
    0f, 
    speed * Input.GetAxis("Vertical") * Time.deltaTime, 
    Space.World);
请注意末尾的
Space.World
参数,以设置世界坐标系。
您可以在Unity文档中找到更多信息:

Ah!我不知道转换的最后一个参数。Translate类,谢谢!