Search Unity

Code moves object at a 40 and -40 degree angle as intended. However, I am not sure why it works.

Discussion in '2D' started by CapnFedora, Aug 3, 2019.

  1. CapnFedora

    CapnFedora

    Joined:
    Jul 21, 2019
    Posts:
    3
    I have written code to move bullets coming from two guns aimed at 40 and -40 degree angles. Each bullet propels itself at the appropriate angle. However, I am not sure why it works, as I'm incredibly new to programming in Unity. Can someone explain to me what exactly it is that's going on here?

    Here is the code for the left bullet:

    Code (CSharp):
    1. public float speed = 20f;
    2.     public Rigidbody2D rb;
    3.  
    4.     void Start()
    5.     {
    6.        
    7.         transform.Rotate(0, 0, -40);
    8.  
    9.        
    10.  
    11.         rb.velocity = transform.right + transform.up  * speed;
    12.  
    13.     }
    And here is the code for the right:

    Code (CSharp):
    1. public float speed = 20f;
    2.     public Rigidbody2D rb;
    3.  
    4.     void Start()
    5.     {
    6.        
    7.        
    8.         transform.Rotate(0, 0, 40);
    9.         rb.velocity = -transform.right + transform.up * speed;
    10.     }
    11.  
    The line I don't understand is this:
    Code (CSharp):
    1. rb.velocity = -transform.right + transform.up * speed;
    . Why does that equation move the bullet in that manner?
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    transform.right is the local (depends on the gameobject) vector with length 1.
    woco.png



    -transform.right + transform.up - this is just the sum from the two vectors and it is a new vector.
    add.png