Search code examples
unity-game-enginerotationcollision-detectiongameobject

Unity BoxCollider2D rotation not the same as GameObject rotation


I'm having a bit of an issue with a BoxCollider2D I have on my GameObject. When I rotate the GameObject, the BoxCollider2D rotates with it, but not as fast. Is there a way to get the BoxCollider2D to move at the same rate as the GameObject? I feel like I'm missing something obvious.

Before Rotation
After Rotation

Below is my code for the movement of the player:

 Animator anim;
 Rigidbody2D rbody;
 float speed = 0f;
 public float moveSpeed = 0.6f;
 public float acceleration = 0.2f;
 public int turnSpeed = 20;
 bool sails = false;

 // Use this for initialization
 void Start () {

     anim = GetComponentInChildren<Animator> ();
     rbody = GetComponent<Rigidbody2D> ();
 }

 // Update is called once per frame
 void Update () {

     if (sails) {
         rbody.transform.Translate (transform.right * (speed * Time.deltaTime));
         speed += acceleration * Time.deltaTime;

         if (speed > moveSpeed)
             speed = moveSpeed;

         if (Input.GetKey (KeyCode.LeftArrow)) {
             rbody.transform.Rotate (0,0,turnSpeed * Time.deltaTime);
         }

         if (Input.GetKey (KeyCode.RightArrow)) {
             rbody.transform.Rotate (0,0,-turnSpeed * Time.deltaTime);
         }
     }

     if (!sails) {

         rbody.transform.Translate (transform.right * (speed * Time.deltaTime));
         speed += -acceleration * Time.deltaTime;

         if (speed < 0f)
             speed = 0f;
     }

     if (Input.GetKeyDown (KeyCode.Space)) {
         sails = !sails;
         anim.SetBool ("sailsDown", sails);
     }
 }

Solution

  • The problem is not your rotation, but how you are applying the the movement. You are using transform.right which is the local right of the object. But then, when applying the translate you apply it to the object locally too.

    For example, if your ship is facing down (rotation.Z = -90), transform.right value is (0,-1,0), in World coordinates this is equal to "down".

    But then you use rbody.transform.Translate(vector) which will translate the object using local coordinates. This means that if you pass it the "down" vector, it will be moving down locally, which in the case of being rotated -90 inthe Z axis, means moving "left" relative to the world.

    You have to change this line:

    rbody.transform.Translate(transform.right * (speed * Time.deltaTime));
    

    To:

    rbody.transform.Translate(transform.right * (speed * Time.deltaTime),Space.World);
    

    Or:

    rbody.transform.Translate(Vector2.right * (speed * Time.deltaTime));