Search Unity

Is it possible to rotate a gameObject to face its moving direction when using 'bounciness'?

Discussion in '2D' started by AV_Corey, Oct 26, 2016.

  1. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    I have an arrow and I have a mirror.

    The mirror has a BoxCollider2D attached with a PhysicsMaterial2D that has the bounciness property set to 1.

    The arrow hits the mirror and is redirected in the correct direction but the facing direction of the arrow obviously stays the same.

    Is there a way to rotate the arrow to always face the direction it is moving when using the bounciness property or would I need to write my own script to handle the redirection instead of using bounciness?
     
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    If the arrow rotation is purely visual, you can put the rendering components as a child to the physics components and write a quick script to get the angle of velocity and apply it to eulerAngles.z. Keep in mind that you'll have to account for angular ambiguity after calculating the angle of velocity.

    Will this work for you?
     
    AV_Corey likes this.
  3. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    Thanks for the reply, although this solution sounds a bit out of my league for me to implement. I may just change the arrow sprite to something spherical so it looks no different no matter what way it is moving and call that a solution lol :p
     
  4. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    Don't give up yet! We can help-- I just did this for a spike projectile in my project, and I promise it's only a couple lines of code at worst.

    Try this: Get the angle of the velocity with Vector2.Angle():

    Code (CSharp):
    1. Rigidbody2D rBody = GetComponent<Rigidbody2D>();
    2. float vAngle = Vector2.Angle(Vector2.Right, rBody.velocity);    //Using Vector2.Right for the "from" argument assumes the arrow faces to the right when it's not rotated
    Now just set the z rotation of the object to this angle using Transform.eulerAngles:

    Code (CSharp):
    1. Transform.eulerAngles = new Vector3(0, 0, vAngle);    //x- and y-angles are 0 because it's 2D
    Do all of this in Update(). This will get you started, but you'll notice it behaving weird when it tries to go certain directions. This is the problem I mentioned before ("angular ambiguity"), caused in this case because Vector2.Angle() returns the smaller of the two angles between the input vectors. This is fixed by checking whether the y-velocity is negative, and if it is, using the negative of vAngle instead (same as 360-vAngle).
     
    Last edited: Oct 26, 2016
    AV_Corey likes this.
  5. AV_Corey

    AV_Corey

    Joined:
    Jan 7, 2016
    Posts:
    122
    Thankyou, I will try and implement this some time today :)