This is driving me nuts. I have this code:
void FixedUpdate () {
Vector3 desiredForward = Camera.main.transform.position-transform.position;
Quaternion desiredRotation = Quaternion.LookRotation(desiredForward);
float amount = Quaternion.Angle(transform.rotation, desiredRotation) / 180 * Time.fixedDeltaTime;
GetComponent<Rigidbody>().AddTorque(desiredRotation * Vector3.up * amount, ForceMode.Acceleration);
GetComponent<Rigidbody>().AddTorque(desiredRotation * Vector3.right * amount, ForceMode.Acceleration);
GetComponent<Rigidbody>().AddTorque(desiredRotation * Vector3.forward * amount, ForceMode.Acceleration);
}
All I want to do is for the GameObject to rotate and look at the main camera, via Physics using AddTorque() on its Rigidbody.
I know how to do this by modifying the transform directly but I want to do it via Physics. I know it’s possible but I just can’t figure out how to do it! I crave this knowledge.
If I do this instead of the last four lines…
transform.rotation = desiredRotation;
…then the GameObject will look right at the main camera, so I know the quaternion is correct. But how do I manipulate the Rigidbody to gradually rotate to the desiredRotation over several fixed updates?
- The first behaviour I desire is for the GameObject to rotate to the desired rotation and then go back and forth (always “passing through” the transform.forward that makes it look straight at the main camera).
- The second behaviour is that it should smoothly slows down its rotation --using only AddTorque()-- and then finally stops at the desired rotation.
- But first things first, having it swing back and forth at the desired rotation feels like the key to solving this problem.
Remember that I don’t want to “cheat” by modifying the angular velocity or transform directly. I don’t want to use rigidbody.MovePosition() or rigidbody.MoveRotation() or anything like that. I just want to see how to rotate a GameObject with physics only, for learning purposes.
I think the first step is to figure out the direction it wants to rotate on the “rotational sphere”. Multiplying desiredRotation with for example Vector3.up is probably fine (?) but I need to also multiply it with -1 if the desired rotation is downwards, but I can’t figure out a good way to do it.
Like I said, this is driving me nuts. I really hope someone can help me!