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.
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
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.t Time.deltaTime
.
- Use LeanTween plugin (free, available on Asset store) or Animator component (with two state based animation: Rotate, Steady) to rotate.