0

我正在 Unity 中创建一个 3D 游戏,并且我有一个脚本可以让玩家用鼠标环顾四周。为了让玩家朝着他们正在寻找的方向移动,我使用了 transform.forward。我的问题是,当他们看着天花板并按“W”(向前)时,他们开始升到空中。基本上我需要知道是否有一种方法或子方法transform.forward允许仅在 x 和 z 轴上移动。

这是我的移动脚本(C#):

if (transform.rotation.x < -10)
        {
            //do no forward or backward movement
            Debug.Log("Rotation too great to forward move...");
            tooGoodForMovement = true;

        }
        else
        {
            tooGoodForMovement = false;
            if (Input.GetKey(KeyCode.W))
            {
                //Forward
                player.velocity = (transform.FindChild("Main Camera").transform.forward * moveSpeed);
            }
            if (Input.GetKey(KeyCode.S))
            {
                //Back
                player.velocity = (-transform.FindChild("Main Camera").transform.forward * moveSpeed);
            }
        }
        if (Input.GetKey(KeyCode.A))
        {
            //Left
            player.velocity = -transform.FindChild("Main Camera").transform.right * moveSpeed;
        }

        if (Input.GetKey(KeyCode.D))
        {
            //Right
            player.velocity = transform.FindChild("Main Camera").transform.right * moveSpeed;
        }
4

1 回答 1

2

尝试将速度矢量设置为临时变量并将 Y 重置为零。

Transform camera;

void Start()
{
    //Cache transform.FindChild so that we don't have to do it every time
    camera = transform.FindChild("Main Camera");
}

然后在您的其他功能中:

Vector3 velocity = Vector3.zero;

if (transform.rotation.x < -10)
{
    //do no forward or backward movement
    Debug.Log("Rotation too great to forward move...");
    tooGoodForMovement = true;
}
else
{
    tooGoodForMovement = false;
    if (Input.GetKey(KeyCode.W))
    {
        //Forward
        velocity = camera.forward * moveSpeed;
    }
    if (Input.GetKey(KeyCode.S))
    {
        //Back
        velocity = -camera.forward * moveSpeed;
    }
}
if (Input.GetKey(KeyCode.A))
{
    //Left
    velocity = -camera.right * moveSpeed;
}

if (Input.GetKey(KeyCode.D))
{
    //Right
    velocity = camera.right * moveSpeed;
}

velocity.Y = 0;
player.velocity = velocity;
于 2016-11-04T22:33:53.303 回答