简体   繁体   English

如何在 Unity 中使玩家垂直(前后)移动 3D

[英]How to make vertical (front and back) movement of a player in Unity 3D

I'm building a game project in Unity 3D, I managed to make player move left or right but facing problem in making the player move front and back.我正在 Unity 3D 中构建一个游戏项目,我设法让玩家向左或向右移动,但在让玩家前后移动时遇到了问题。

It is the part of the code.它是代码的一部分。 What to do to make player move front and back?如何使玩家前后移动? I have used the getaxis function, but still not working.我已经使用了 getaxis function,但仍然无法正常工作。

void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jump = true;
        }
        horizontalInput = Input.GetAxis("Horizontal");
        verticalInput = Input.GetAxis("Vertical"); ;
    }
    private void FixedUpdate()
    {
        GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput, GetComponent<Rigidbody>().velocity.y, 0);
        

        if (jump==true)
        {
            GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
            jump = false;
        }
    }
}
private void FixedUpdate()
{
    GetComponent<Rigidbody>().velocity = new Vector3(horizontalInput, GetComponent<Rigidbody>().velocity.y, verticalInput);
    if (jump==true)
    {
        GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
        jump = false;
    }
}

If you instead of setting the z-axis of the velocity vector to zero, you set it to the value of the verticalInput this will allow the player to move forward and backward based on the value of the "Vertical" axis.如果您不是将速度矢量的 z 轴设置为零,而是将其设置为 verticalInput 的值,这将允许玩家根据“垂直”轴的值向前和向后移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM