0

我是 Unity 中 C# 编程的新手,在 z 轴上移动时会出现一些问题。问题是当我松开向上按钮时我继续移动。但是,当我在 x 轴上移动时,这很好,因为放开按钮会停止播放器。代码如下:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
public Vector3 motion = new Vector3();
private CharacterController controller;

private bool onGround;

private float xRot, yRot;
public static float X_ROTATION = 0;
public static float Y_ROTATION = 0;
private const float lookSpeed = 2.0f;

public void Start() {
    controller = GetComponent<CharacterController>();
}

public void FixedUpdate() {
    if(Screen.lockCursor) {
        Vector3 impulse = new Vector3();
        if(Input.GetKey(KeyCode.W)) impulse.z+=1;
        if(Input.GetKey(KeyCode.A)) impulse.x-=1;
        if(Input.GetKey(KeyCode.S)) impulse.z-=1;
        if(Input.GetKey(KeyCode.D)) impulse.x+=1;

        if(impulse.sqrMagnitude > 0) {
            motion += Quaternion.Euler(new Vector3(0, xRot, 0)) * impulse.normalized * 0.05f;
        }

        if(onGround) {
            if(Input.GetKey(KeyCode.Space)) {
                motion.y += 0.2f;
            }
        }

        motion.y -= 0.015f;
        Vector3 oldMotion = motion;
        Vector3 oldPos = controller.transform.localPosition;
        controller.Move(motion);
        Vector3 newPos = controller.transform.localPosition;
        motion = newPos - oldPos;
        onGround = oldMotion.y < -0.0001f && motion.y >= -0.0001f;
        motion.x *= 0.8f; 
        motion.y *= 0.8f;
    }
}

public void Update() {
    if(Screen.lockCursor && Input.GetKeyDown(KeyCode.Escape)) {
        Screen.lockCursor = false;  
    }

    if(!Screen.lockCursor && Input.GetMouseButtonDown(0)) {
        Screen.lockCursor = true;   
    }

    if(Screen.lockCursor) {
        xRot += Input.GetAxis("Mouse X") * lookSpeed;
        yRot -= Input.GetAxis("Mouse Y") * lookSpeed;

        if(yRot < -90) yRot = -90;
        if(yRot > 90) yRot = 90;
        if(xRot < -180) xRot += 360;
        if(xRot >= 180) xRot -= 360;

        controller.transform.localRotation = Quaternion.Euler(new Vector3(yRot, xRot, 0));
    }

    Player.X_ROTATION = xRot;
}

}

4

2 回答 2

3

您已编码的 FixedUpdate() 中的最后几个语句-

motion.x *= 0.8f;
motion.y *= 0.8f;

还应该包含

motion.z *= 0.8f;

也许你不需要-

motion.y *= 0.8f;
于 2013-08-11T06:42:41.350 回答
1

正如 Gkills 所说,你应该在最后修复motion.yfor的“耗尽” motion.z

此外,您可能应该想要交换

motion += Quaternion.Euler(new Vector3(0, xRot, 0)) * impulse.normalized * 0.05f;

为了

motion += transform.rotation * impulse.normalized * 0.05f;

然后将脉冲.y 组件清零以防止玩家飞行。

最后,您可能希望Time.deltaTime在更新中使用(因此鼠标外观与帧速率无关)

于 2013-08-11T07:56:16.307 回答