- Home /
Rotate Rigidbody 2D towards velocity
I'm attempting to use this code from a previous AskUnity question to rotate the nose (the right edge) of a rectangle(Rigidbody2d) towards the velocity it is currently travelling.
"transform.rotation=Quaternion.SetLookRotation(velocity);"
I've converted the current velocity of my Rigidbody from a vector2 to a vector 3, but because it rotates the X axis, and not the Z axis, as soon as it rotates in the 3D space the item disappears. How would i rotate the right edge towards the velocity it's travelling?
Thanks!
Answer by robertbu · Feb 17, 2014 at 01:27 PM
Here is a bit of code that will rotate the object to face the direction of the velocity over time:
function Update () {
var dir = rigidbody2D.velocity;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
var q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotateSpeed * Time.deltaTime);
}
'rotateSpeed' is a variable you define and whose value is in degrees per second. If you want eased movement, replace 'RotateTowards' with 'Slerp' and adjust 'rotateSpeed' downwards a bunch.
Really appreciate you taking the time to respond to this.
It works and the item points in roughly the right direction but it's very very twitchy even with the rotationSpeed slowed right down and with Slerp applied.
It's constantly vibrating and adjusting the rotateSpeed doesn't seem to affect it, ins$$anonymous$$d it changes the angle it's pointing at.
Any ideas how I can smooth out this twitch?
Thanks again.
Is your velocity changing frame to frame? If so, maybe you want to average the velocity of a fixed number of frames. And you did say you tried Slerp() ins$$anonymous$$d of RotateTowards()? If averaging does not solve the problem, post a copy of your movement code and I'll play a bit.
Your answer
Follow this Question
Related Questions
i have rotated an gameobject but the axis of the object did not change 2 Answers
2D Rotate towards GameObject acting odd. 2 Answers
2D Sprite/object rotation changing despite telling it not to 0 Answers
Unity C# 2D Adding Velocity on rotation 1 Answer
why can't i divide rb2D.velocity.x by rb2D.velocity.x? [Fixed] 1 Answer