- Home /
Rotate 3D Object using rigidbody.rotation rather than transform.rotate
Hello everyone,
I am trying to rotate a 3d object based on touch using its rigidbody rather than transform, so i won't violate physics, and to be able to collide properly with other objects while rotating.
This code works perfectly using Transform.Rotate, but I am not able to change it to use RigidBody.Rotation.
I would appreciate any help how can i do this! Thanks.
public class RotateObject : MonoBehaviour
{
public float Velocity = 0.5f;
public float VelocityFactor = 1;
Vector3 mPrevPos = Vector3.zero;
Vector3 mPosDelta = Vector3.zero;
public Vector3 lastDirectionAsResisting;
bool isTouchActive;
private void FixedUpdate()
{
if (Input.GetMouseButton(0))
{
if (isTouchActive == false)
{
mPrevPos = Input.mousePosition;
isTouchActive = true;
}
mPosDelta = Input.mousePosition - mPrevPos;
ApplyRotation(mPosDelta);
mPrevPos = Input.mousePosition;
}
else
{
isTouchActive = false;
}
}
void ApplyRotation(Vector3 delta)
{
delta *= Velocity * VelocityFactor;
if (Vector3.Dot(transform.up, Vector3.up) >= 0)
{
transform.Rotate(transform.up, -Vector3.Dot(delta, Camera.main.transform.right), Space.World);
}
else
{
transform.Rotate(transform.up, Vector3.Dot(delta, Camera.main.transform.right), Space.World);
}
transform.Rotate(Camera.main.transform.right, Vector3.Dot(delta, Camera.main.transform.up), Space.World);
}
public void CapturePreviousDelta()
{
lastDirectionAsResisting = Vector3.down;
}
}
Answer by Ermiq · Nov 16, 2019 at 08:57 AM
To rotate a rigidbody you'd better use Rigidbody.MoveRotation() to get advantage of the rigidbody interpolation setting to get smooth rendering with no jittering.
By rotating a rigidbody with rigidBody.rotation you just apply the rotation immediately therefore you might violate physics. Use MoveRotation() when you need to rotate the rigidbody in update loops.
To use this you'll need a rotation quaternion. Something like this:
Quaternion rotationToMove;
void ApplyRotation(Vector3 delta)
{
delta *= Velocity * VelocityFactor;
if (Vector3.Dot(transform.up, Vector3.up) >= 0)
{
// get the rotation which rotates 'x' degrees around the 'axis'.
// 'x' will be your dot product, 'axis' - transform's up vector.
rotationToMove = Quaternion.AngleAxis(-Vector3.Dot(delta, Camera.main.transform.right), transform.up);
}
else
{
rotationToMove = Quaternion.AngleAxis(Vector3.Dot(delta, Camera.main.transform.right), transform.up);
}
rigidBody.MoveRotation(rotationToMove);
}
Not sure why you rotate the transform again then relative to the camera though.
Your answer
Follow this Question
Related Questions
How to make a cube turn in the direction it is moving? 1 Answer
How do I stop a rigidbody from rotating after colliding with another object? 1 Answer
Object is passing from colliders when swipe with rigidbody.position 1 Answer
Plane CollisionWheels keep jumping around 0 Answers
Rotation of enemies 1 Answer