I'm making a 2D game in Unity. Basically there's just a rocket that goes where ever the user touches. With the code that i have right now, the rocket instantly rotates towards the point and moves there straight.

Vector3 dir = targetPos - transform.position;
float rotZ = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
thrust = 10.0f;
rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.up);

This code is placed in the Update function.

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.


You could make a coroutine and make it delay for some time and then activate the rotation function. The spawning position may be randomized using random.range

  • \$\begingroup\$ What do you mean by spawning position? \$\endgroup\$ – Jaspreet Singh Jul 29 '15 at 17:17
  • \$\begingroup\$ Sorry for that my bad I meant the direction could be randomized. \$\endgroup\$ – Vadim Tatarnikov Jul 29 '15 at 17:18
  • \$\begingroup\$ Why would i randomize the direction? I want the rocket to move where user touches \$\endgroup\$ – Jaspreet Singh Jul 29 '15 at 17:20
  • \$\begingroup\$ Cause that's how I understood the last part of your question when you said "which ever direction" \$\endgroup\$ – Vadim Tatarnikov Jul 29 '15 at 17:21
  • \$\begingroup\$ I apologize once more for misunderstanding English isn't my first language \$\endgroup\$ – Vadim Tatarnikov Jul 29 '15 at 17:22

What you need to do is control the rocket using steering behavior.

At every frame. You want to move the rocket towards its transform.forward, it might be transform.up in the case of 2d.

Then you want to lerp the rockets rotation towards the target location

transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(target), rotationSpeed);

RotationSpeed should be a number between 0 and 1. Like 0.3 for a fairly slow rotation

  • \$\begingroup\$ This is what i did in Update function targetPos = Input.mousePosition; targetPos = Camera.main.ScreenToWorldPoint(targetPos); rb.AddForceAtPosition(transform.up * Thrust, transform.up); transform.rotation = Quaternion.Lerp(transform.rotation,Quaternion.LookRotation(targetPos), 0.4f); But as soon as i touch the screen, the rocket starts spinning really fast and skewing. \$\endgroup\$ – Jaspreet Singh Jul 29 '15 at 20:57

This worked for me

float rotationSpeed = 1;
transform.rotation = Quaternion.RotateTowards(transform.rotation,Quaternion.euler(0,0,-rotZ), rotationSpeed);

rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.position - transform.up);

Thanks everyone who helped!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.