Search Unity

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

Discussion in 'Scripting' started by EliteWalrus, Oct 20, 2014.

  1. EliteWalrus

    EliteWalrus

    Joined:
    Aug 16, 2014
    Posts:
    44
    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?

    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var moveSpeed : float = 10;
    4. var maxMoveSpeed : float = 20;
    5. var turnSpeed : float = 50;
    6.  
    7. function FixedUpdate () {
    8.     if (Input.GetKey (KeyCode.W)) {
    9.         if (rigidbody2D.velocity.y <= maxMoveSpeed) {
    10.             rigidbody2D.velocity.y += moveSpeed;
    11.         } else {
    12.             rigidbody2D.velocity.y = maxMoveSpeed;
    13.         }
    14.     }
    15.  
    16.     if (rigidbody2D.velocity.y >= 0.00001) {
    17.         rigidbody2D.velocity.y -= moveSpeed / 8;
    18.     }
    19.  
    20.     if (Input.GetKey (KeyCode.D)) {
    21.         transform.Rotate (Vector3.back * turnSpeed * Time.fixedDeltaTime);
    22.     }
    23.  
    24.     if (Input.GetKey (KeyCode.A)) {
    25.         transform.Rotate (Vector3.back * turnSpeed * -1 * Time.fixedDeltaTime);
    26.     }
    27. }
    28.  
    29.  
    30.  
     
  2. Habitablaba

    Habitablaba

    Joined:
    Aug 5, 2013
    Posts:
    136
    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.
     
    Last edited: Oct 20, 2014
  3. EliteWalrus

    EliteWalrus

    Joined:
    Aug 16, 2014
    Posts:
    44
    That fixed it, Thanks.
     
    Habitablaba likes this.