How to add velocity to the direction an object is facing?

I have made a script that adds velocity to the y axis, but I would like to add velocity to the direction it’s facing rather than just adding velocity to the y axis. How can this be done?

#pragma strict

var moveSpeed : float = 10;
var maxMoveSpeed : float = 20;
var turnSpeed : float = 50;

function FixedUpdate () {
    if (Input.GetKey (KeyCode.W)) {
        if (rigidbody2D.velocity.y <= maxMoveSpeed) {
            rigidbody2D.velocity.y += moveSpeed;
        } else {
            rigidbody2D.velocity.y = maxMoveSpeed;
        }
    }
  
    if (rigidbody2D.velocity.y >= 0.00001) {
        rigidbody2D.velocity.y -= moveSpeed / 8;
    }
  
    if (Input.GetKey (KeyCode.D)) {
        transform.Rotate (Vector3.back * turnSpeed * Time.fixedDeltaTime);
    }
  
    if (Input.GetKey (KeyCode.A)) {
        transform.Rotate (Vector3.back * turnSpeed * -1 * Time.fixedDeltaTime);
    }
}

You want to use transform.forward, transform.up, or transform.right instead of the Vector3 version you are using.

Vector3 acts in world space, and transform acts in local space, so transform.forward will always be forward relative to the orientation of the object.

3 Likes

That fixed it, Thanks.

1 Like