Search Unity

Rigidbody2D rotation using MoveRotation

Discussion in '2D' started by directusgames, Mar 13, 2016.

  1. directusgames

    directusgames

    Joined:
    May 8, 2015
    Posts:
    14
    Hi guys,

    I'm having issues with trying to rotate a Rigidbody2D towards another object (slowly) using MoveRotation. I've been doing this using transform.rotation previously but performance-wise I've read it's better to use MoveRotation.

    This is the code I was using previously (in Update) to calculate the vector from the object to the target object and then rotate:
    Code (CSharp):
    1.  
    2.        Vector3 diff = target.transform.position - transform.position;
    3.  
    4.         diff.Normalize();
    5.      
    6.         float rot_z = (Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg);
    7.      
    8.         Quaternion newRot = Quaternion.Euler(new Vector3(0,0,rot_z - 90));
    9.         transform.rotation = Quaternion.RotateTowards(transform.rotation, newRot, Time.deltaTime * 150f);
    10.  
    I'm having difficulty trying to modify this code in a way that uses Rigidbody2D.MoveRotation and still achieves the same effect. Does anyone have any ideas?

    Here's the movement I currently have. Each frame the drones are moving in the forward direction while rotating towards an enemy. After they fire a shot the rotation is paused briefly.

     
  2. Zaflis

    Zaflis

    Joined:
    May 26, 2014
    Posts:
    438
    It looks to me the rotation is working then. You're not showing the code that's related to the "pause" though.

    I was thinking the both ships may be doing rapid left-right-left-r... swapping in some sort of loop. When other ship turns left and other turns right it determines it has to counter it other side first so it changes its mind and turns other direction... So maybe if you give a small delay on when it can switch the side it can turn to? If it is swapping like that it is so fast that eye can't see, it looks like flying straight line.
     
  3. laurentlavigne

    laurentlavigne

    Joined:
    Aug 16, 2012
    Posts:
    6,364
    I had to reverse the vector diff when diff.x <0 ... why? no idea but it works :D

    Code (CSharp):
    1.     void FixedUpdate ()
    2.     {
    3.         Vector3 diff = GetComponent<Rigidbody2D> ().velocity.normalized;
    4.         diff = diff.x < 0 ? -diff : diff;
    5.         float rot_z = (Mathf.Atan2 (diff.y, diff.x) * Mathf.Rad2Deg);
    6.         rigid.MoveRotation (WrapAngle (rot_z));
    7.     }
    8.