Alright, I've been stressing over this a bit and I thought I'd ask around and see if someone else had a solution. I have a Rigidbody with a given mass, torque, and angular drag. I want to give this object a set of angles and have it rotate to face those angles. So far I have no problem telling the object "this is where you need to go," and having it apply torque in the right directions, but if I do that until I reach the target angles, it will go past them as it decelerates. I'd like to calculate the exact point at which it should stop applying torque in order to come to a stop at the correct rotation. Thoughts?

I'm working on the same thing for my AI right now, so I think I can help with some ideas. If you know how much torque is available and moment of inertia of your object you can calculate how much angular acceleration it will generate based on this formula: a = T/I We also know, that formula for distance in accelerated movement is: v=at, so applying this to curcular motion gives us: w = at so: t = w/a where w = angular speed (which we know from rigidbody.angularvelocity) Now, that we know how much time will it take to stop rotation we can calculate how many angles will it take: angles = (at^2)/2 or in single equation: angles = ((T/I)*(w/(T/I))^2)/2 So, you can apply torque in direction of turn if angles (in radians) to turn are greater than angles. If not, apply opposite torque until angular velocity is 0. This is how it should work in theory.

Oh wow, thank you - that's exactly what I was looking for! Do you account for angular drag? Or do you just not use it in your project?

I've got it partially working for one axis. Here's my test code: Code (CSharp): using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(Collider))] public class Spinny : MonoBehaviour { Rigidbody rb; float inertia, torque; float timeToStop; public float AngularAcceleration = 6.28f; void Awake() { rb = GetComponent<Rigidbody>(); } void Start() { inertia = rb.inertiaTensor.z; torque = inertia * AngularAcceleration; } void Update() { if (Input.GetKey(KeyCode.LeftArrow)) { rb.AddTorque(Vector3.forward * torque); } else if (Input.GetKey(KeyCode.A)) { timeToStop = rb.angularVelocity.z / AngularAcceleration; } if (timeToStop > 0f) { rb.AddTorque(Vector3.back * torque); timeToStop -= Time.deltaTime; } } } The next problem seems to be dealing with the tiny bit of leftover momentum. Is there a way to do that without just setting angularVelocity to 0?

Well, looking at your script you don't really need to calculate torque if you want constant deceleration. You just need to use ForceMode.Acceleration. And, if'm honest I'd use a slightly a different approach to ensure that your object stops: Code (CSharp): using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(Collider))] public class Spinny : MonoBehaviour { Rigidbody rb; float drag; bool stop; public float AngularAcceleration = 6.28f; void Awake() { rb = GetComponent<Rigidbody>(); } void Start() { drag = rb.angularDrag; } void FixedUpdate() { if (Input.GetKey(KeyCode.LeftArrow)) { rb.AddTorque(Vector3.forward * AngularAcceleration, ForceMode.Acceleration); } else if (Input.GetKey(KeyCode.A)) { stop = true; } if (rb.angularVelocity.z>0) { if (stop){ rb.AddTorque(Vector3.back * Mathf.Min(AngularAcceleration, rb.angularVelocity.z), ForceMode.Acceleration); } }else{ stop = false; } } }

I should have specified that that was just an experiment to make sure I was following along with the mechanics! It's all a little brain-bending for me so I'm trying to go one step at a time. The ultimate goal is still to have something that you can set to a specific rotation and have it figure out how to get there, rather than having to press an arrow key. I have another update that I'll post in a bit.

Alright. Here's my latest attempt. The formula to figure out how long it should take to bring the object to a halt works fine, but the second part, to find how many radians it will take, seems off. The error grows exponentially the faster the object spins. (Of interest: Unity seems to have a built-in speed limit of 7 rad/s.) Code follows: Code (CSharp): using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(Collider))] public class Spinny : MonoBehaviour { Rigidbody rb; float inertia, torque; float timeToStop, stopTimer; float anglesToStop, lastRotation, stopAngles; bool stopping; public float AngularAcceleration = 3.14f; void Awake() { rb = GetComponent<Rigidbody>(); } void Start() { inertia = rb.inertiaTensor.z; Debug.Log("Inertia: " + inertia.ToString("F2") + " kg*m²."); torque = inertia * AngularAcceleration; Debug.Log("Torque: " + torque.ToString("F2") + " N*m."); stopping = false; } void FixedUpdate() { if (!stopping && Input.GetKey(KeyCode.LeftArrow)) { rb.AddTorque(Vector3.forward * torque); } if (stopping && timeToStop > 0f) { rb.AddTorque(Vector3.back * torque); timeToStop -= Time.deltaTime; stopTimer += Time.deltaTime; stopAngles += Mathf.Abs((transform.eulerAngles.z * Mathf.Deg2Rad) - lastRotation); } else if (stopping && timeToStop <= 0f) { rb.angularVelocity = Vector3.zero; Debug.Log("Stopped. It took " + stopTimer.ToString("F2") + " s and " + stopAngles.ToString("F2") + " rad."); if (!Mathf.Approximately(0f, rb.angularVelocity.z)) { Debug.Log("Oops! Leftover Angular Velocity: " + rb.angularVelocity.z + " rad/s."); } stopping = false; } lastRotation = transform.eulerAngles.z * Mathf.Deg2Rad; } void Update() { if (Input.GetKeyDown(KeyCode.A)) { Debug.Log("Stopping!"); Debug.Log("Current Angular Velocity: " + rb.angularVelocity.z.ToString("F2") + " rad/s."); timeToStop = rb.angularVelocity.z / AngularAcceleration; Debug.Log("Estimated Time to Stop: " + timeToStop.ToString("F2") + " s."); stopTimer = 0f; anglesToStop = Mathf.Pow(AngularAcceleration * timeToStop, 2f) / 2f; Debug.Log("Estimated Angles to Stop: " + anglesToStop.ToString("F2") + " rad."); stopAngles = 0f; stopping = true; } } } Edit: In plain english, what this is supposed to do (so far) is figure out for how many radians it will have to apply reverse torque in order to bring it to a stop. Once that works, the next step would be to use that calculation to determine when to call for a stop in order to reach a specific rotation. Does that make sense?

You say that you want to know when to 'stop applying torque', but what about applying a braking torque as you approach the target rotation? This simple approach is used in PID controllers which are designed for exactly this situation. So your object has an angular velocity which gives it momentum that takes it past the target rotation. If you try to solve this simply by stopping the application of torque at the appropriate time, you won't be able to rotate quickly as you will have to wait for the momentum to die down, which could take a long time. What you need to do is apply a braking/damping force. First of all, the P in PID stands for Proportional, and this is what you probably have already implemented, a torque that is applied proportional to how far away the object is from the desired rotation. The D in PID is what you're looking for, it stands for Derivative (rate-of-change, i.e. velocity) and it refers to a torque that is applied to counter the current velocity of the object, in this case the angular velocity. It basically amounts to a damping force and is extremely simple to implement. All you have to do is get the angular velocity of your object, and apply a torque in the opposite direction to that velocity that is proportional to that velocity. For example: Code (CSharp): public float dampingCoefficient; // Get the local angular velocity Vector3 localAngularVelocity = myTransform.InverseTransformDirection(myRigidbody.angularVelocity); // Calculate damping torques based on that angular velocity and apply it in the opposite direction (negative) Vector3 dampingTorque = localAngularVelocity * -dampingCoefficient; myRigidbody.AddRelativeTorque(dampingTorque); Then you just tweak the damping coefficient until you're happy with the effect.

I meant "apply stopping torque." Physics! Your method will definitely bring the body to a stop, but I'm not sure how it can account for doing so at a specific rotation, which was the problem I was trying to solve. I. e., how can I know when to start braking so that my car ends up exactly at the stop line without going over given an arbitrary distance, momentum, and stopping force?

If you want to bring your object to a stop with mathematical precision, it is probably a bit more complicated. However If you use the correct coefficient with the method I showed you, oscillation is virtually non-existent (and certainly not visible at all). Can I you give a little more context to your issue? Is it a vehicle of some kind?

Sure. Movement and the related calculations have always been a pain for me, so I'm trying to go back and figure them out a step at a time. At the moment it's an asteroids-style ship floating around in frictionless space. Although I have key controls in my code at the moment, I'd like to just be able to tell the ship "turn to face this direction" and have it turn to face that direction. In order to make this arrangement as extensible as possible, I'd also like to be able to define the ship's mass and maximum torque and have it work backwards from there by itself. Does that make sense?

I've written quite a few spaceship controllers, I can tell you! You can see the WIP of what I'm working on at the moment in my sig. In working on the AI, I tried a lot of different approaches to the control system - all of them physics-based using forces. I'm not sure if your game is 3D but I will assume so. To avoid gimbal lock (I assume you've run into it already) you need to set up a hierarchy for the different axes. E.g., for a turret-style movement you might yaw until your nose is near the target before pitching toward it. The key thing to remember with gimbal lock is that all the problems occur when some of your rotations are ~90 degrees or more from the target. That is where euler angles can start becoming difficult to deal with. So you should only apply torques for a particular axis when the rotations on the other axes that are higher up in the hierarchy are well below 90 degrees from their target. For example, my missile controller yaws (rotates on the y axis) toward the target, and only when it is well below 90 degrees away from its yaw target (lets say around 75 degrees) I begin to implement pitch. This, together with the damping method I showed you above, makes it possible to rotate toward the target from any starting rotation, and decelerates smoothly as it approaches the target, and doesn't overshoot. Let me know if you have any questions about it, I hope I understood your issue correctly.

Hi again. First, if it's in frictionless environment I'd disable all drag. Makes it more believable and easier to calculate. What I did was creating two separate scripts so that the ship can be controlled by both AI and the player. First script is just a ship controller, which is something like this: Code (CSharp): public float yaw; // other scripts (like AI) access this variable to send command to the ship public float maxTorque; float yawRotationVelocity; float MaxRotVel; void FixedUpdate() { yawRotationVelocity = transform.InverseTranformDirection(rb.angularVelocity.y); //ship's current rotation speed relative in local yaw axis float targetRotation = 0; if (yaw!=0) { targetRotation = yaw * MaxRotVel; }else { targetRotation = 0; } float difference = targetRotation - yawRotationVelocity; float yawTorque = Mathf.Min(Mathf.Abs(difference),maxTorque) * Mathf.Sign(difference); //if difference > maxtorque apply max torque else apply difference rb.addTorque(transform.up,yawTorque); } Second is an AI script in which I use method from my first post to calculate when to stop turning, so the last line in the code should be something like Code (CSharp): if (Mathf.Abs(anglesToStop)<Mathf.Abs(anglesToTarget)) { ShipController.yaw = Mathf.Sign(anglesToTarget); //you can modify this part to make the turn more smooth like yaw = anglesToTarget/90f so that it will apply full torque if target is perpendicular }else { ShipController.yaw = 0; } There might be slight oscillations but if your code is right the AI script will correct itself. Also please keep in mind that I don't have access to Unity ATM so there might be some errors in code but the principle is ok and it works.

If anyone is still interested, I seem to have finally reached a solution (at least for myself!). This is for 2-dimensional rotation. Ship object: Code (CSharp): using UnityEngine; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(Collider))] public class ShipMovement : MonoBehaviour { Rigidbody rb; float heading, bearing; float angularAcceleration, turnSpeed; public float MaxTorque = 7.5f; public float StopThreshold = .5f; Vector3 tVec; void Awake() { rb = GetComponent<Rigidbody>(); } void Start() { Debug.Log("Inertia: " + rb.inertiaTensor.z.ToString("F2") + " kg*m²"); Debug.Log("Max. Torque: " + MaxTorque + " N*m"); angularAcceleration = MaxTorque / rb.inertiaTensor.z * Mathf.Rad2Deg; Debug.Log("Max. Angular Acceleration: " + angularAcceleration.ToString("F2") + "°/s²."); tVec = Vector3.zero; } void FixedUpdate() { turnSpeed = rb.angularVelocity.z * Mathf.Rad2Deg; if (tVec != Vector3.zero) { tVec += rb.velocity * Time.fixedDeltaTime; Debug.DrawLine(transform.position, tVec); var dRot = Quaternion.FromToRotation(transform.up * -1f, (tVec - transform.position)); var difference = 360f - dRot.eulerAngles.z - 180f; var stopDistance = (angularAcceleration * Mathf.Pow(turnSpeed / angularAcceleration, 2f)) / 2f; var torqueDirection = -1f * Mathf.Sign(difference); if (stopDistance >= Mathf.Abs(difference)) { torqueDirection *= -1f; } if (Mathf.Abs(difference) > StopThreshold) { rb.AddTorque(Vector3.forward * torqueDirection * MaxTorque); } else { rb.angularVelocity = Vector3.zero; tVec = Vector3.zero; } } } public void SetTargetVector(Vector3 newTarget) { tVec = newTarget; } } Ship Controller object, child of Ship object: Code (CSharp): using UnityEngine; [RequireComponent(typeof(Collider))] public class PlayerShipMovementController : MonoBehaviour { GameObject ship; Vector3 mousePos; bool isDragging; void Awake() { ship = transform.parent.gameObject; if (ship == null || ship.GetComponent<ShipMovement>() == null) { Debug.LogError("Player Ship Movement Controller has no Parent!"); Debug.Break(); } } void Start() { isDragging = false; } void Update() { mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); mousePos.z = ship.transform.position.z; if (!isDragging) { if (Input.GetMouseButtonDown(0)) { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var rayHit = new RaycastHit(); if (Physics.Raycast(ray, out rayHit, 15f) && rayHit.collider.gameObject == gameObject) { isDragging = true; } } } else if (Input.GetMouseButton(0)) { Debug.DrawLine(ship.transform.position, mousePos); } else { ship.SendMessage("SetTargetVector", mousePos); isDragging = false; } } }