首页 > 解决方案 > 如何在 Unity 中向前移动一个对象?

问题描述

我制作了一个游戏对象并附加了一个脚本。我需要旋转并沿直线移动对象,具体取决于旋转。我转了个弯,但我的运动有问题。有什么解决办法吗?

    //Rotation
    if (Input.GetAxis("Rotation") > 0) {
        transform.Rotate(Vector3.back, turnSpeed * Time.deltaTime);
        
    }
    else if (Input.GetAxis("Rotation") < 0)
    {
        transform.Rotate(Vector3.back, -turnSpeed * Time.deltaTime);
        
    }

    //Velocity
    if (Input.GetAxis("Thrust") != 0) {
            rb.AddForce(Vector3.forward * Time.deltaTime * Speed);
        }
    else if (Input.GetAxis("Thrust") <= 0.1f){
        rb.velocity = new Vector2(0, 0);
    }

标签: c#unity3d

解决方案


Rigidbody.AddForce应用向量作为世界空间中的力。因此,您需要给它一个向量,该向量位于变换前向的世界空间方向。幸运的是,这就像使用transform.forward, transform.up, ortransform.right或其中一个的否定而不是Vector3.forward:

//Rotation
if (Input.GetAxis("Rotation") > 0) {
    transform.Rotate(Vector3.back, turnSpeed * Time.deltaTime);
    
}
else if (Input.GetAxis("Rotation") < 0)
{
    transform.Rotate(Vector3.back, -turnSpeed * Time.deltaTime);
    
}

//Velocity
if (Input.GetAxis("Thrust") != 0) {
        Vector3 frontDirection;
        
        // probably one of these for a 2D game:
        frontDirection = transform.right;
        //frontDirection = -transform.right;
        //frontDirection = transform.up;
        //frontDirection = -transform.up;

        rb.AddForce(frontDirection * Time.deltaTime * Speed);
    }
else if (Input.GetAxis("Thrust") <= 0.1f){
    rb.velocity = new Vector2(0, 0);
}

推荐阅读