- Home /
Rotate and move a 2D object
I'm making a 2D game in Unity. Basically there's just a rocket that goes where ever the user touches.
Vector3 dir = targetPos - transform.position;
float rotZ = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
rb.MoveRotation(-rotZ);
thrust = 10.0f;
rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.up);
This code is placed in the Update function. With this code that i have right now, the rocket instantly rotates towards the point and moves there straight.
I want the rocket to start moving in which ever direction It's currently facing and slowly rotate towards the point as it goes there.
Answer by OrbitGames · Jul 30, 2015 at 09:09 AM
First off, only change dir if the user touches the screen, otherwise it might turn around after the rocket went past targetpos. You can use Quaternion.RotateTowards to slowly rotate towards rotz. (untested)
float rotationSpeed = 1;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.euler(0,0,rotZ), rotationSpeed);
Last Bug is, don't use
rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.up);
the position is actually around the 0 point. You need to use
rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.position - transform.up);
to get a point below your rocket
Thanks! That was exactly what i was looking for. Though i had to change rotZ to -rotZ in Quaternion.RotateTowards. Thanks again!
Answer by NeverHopeless · Jul 30, 2015 at 09:09 AM
You are observing the right behavior since RigidBody.MoveRotation
rotates immediately and RigidBody.MovePosition
moves immediately too.
To move the object you should instead use RigidBody.Velocity
.
rigidbody2d.velocity = new Vector3( x, y, z );
For rotation you have two options as i see:
Use
Update
event to rotate the body w.r.tTime.deltaTime
.Use LeanTween plugin (free, available on Asset store) or Animator component (with two state based animation: Rotate, Steady) to rotate.