在Unity ' transform.forward '中阻止Y轴移动

本文关键字:移动 forward Unity transform | 更新日期: 2023-09-27 18:16:19

我正在用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;
        }

在Unity ' transform.forward '中阻止Y轴移动

尝试将速度矢量设置为临时变量并将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;