Using impulse force to rotate a Rigidbody2D to desired rotation.

in #unity3d5 years ago (edited)

I'm putting this one up because a few people have asked this online but they didn't really get a decent answer.

One night I my ended up struggling on this normally simple problem, at a time of day when I'm not my sharpest (that's my excuse and I'm sticking by it!).

You see there's a Gotcha with Unity which I was too tired to spot until I found a forum post pointing out this inconsistency. Rather than sticking with one, Rigidbody2D's variables and functions work in a mix of degrees and radians. So I spent ages jamming degrees in AddTorque wondering why the hell it wasn't working.

Anyway here's what I got! I hope you find this useful.

float currentRot = m_RB.rotation;
float turn = -((((currentRot + 180f) % 360f + 360f) % 360f) - 180f); // Work out the shortest way to turn to 0 degrees
float angularVelocity = turn / (Time.deltaTime * 4f); // Remove the *4f if you want to snap to target angle
float deltaVelocity = (angularVelocity - m_RB.angularVelocity) * Mathf.Deg2Rad;

m_RB.AddTorque(m_RB.inertia * deltaVelocity, ForceMode2D.Impulse);
Sort:  

Congratulations @firegoat! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You published your First Post
You made your First Vote
You got a First Vote

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @firegoat! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.20
TRX 0.20
JST 0.034
BTC 90227.69
ETH 3079.14
USDT 1.00
SBD 2.93