Muzamil Sajid
Muzamil Sajid

Reputation: 25

Floating Problem With Rigidbody.Velocity in Unity

Below is the code that I am using to move an object in Unity. The rb.Velocity line makes my object float in in Gameplay mode. If I comment out the line then the object falls just fine.

Could someone explain whats happening here?

public class PlayerController : MonoBehaviour
{

    public float forwardVelocity = 0F;
    public float maxSpeed = 180;
    public float acceleratePerSecond = 8.0F;
    public float rotateSpeed = 3.0F;
    private float yaw = 0.0f;
    private float pitch = 0.0f;
    protected Rigidbody rb;
    float timeZeroToMax = 2.5F;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        acceleratePerSecond = maxSpeed / timeZeroToMax;
        forwardVelocity = 0F;

    }

    // Update is called once per frame
    void Update()
    {

            if (Input.GetKey(KeyCode.UpArrow)) //Accelerate The Vehicle
            {
                if (forwardVelocity< maxSpeed)
                {
                forwardVelocity += acceleratePerSecond * Time.deltaTime;

                }

            }


        forwardVelocity = Mathf.Min(forwardVelocity, maxSpeed);


        rb.velocity = transform.forward * forwardVelocity;


        transform.Rotate(0, Input.GetAxis("Mouse X") * rotateSpeed, 0);


        yaw += rotateSpeed * Input.GetAxis("Mouse X");


        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }

}

Upvotes: 0

Views: 1462

Answers (1)

BlackDereker
BlackDereker

Reputation: 66

The transform.forward is a Vector3(0,0,1), that's the problem.

You are setting your y velocity to 0.

Upvotes: 1

Related Questions