- Home /
Slerp to make the right/left side face another object
I'm trying to make the right or left side of an object look at another object, unlike the common approach where you would want the front of an object to face another object. But the code below instantly snaps the object to the new rotation, and I've been unable to add a gradual rotation (Slerp)
Vector3 direction = (player.position - transform.position).normalized;
transform.right = direction;
Would someone please explain how to add a Slerp in this example?
Answer by Magso · Apr 22, 2019 at 08:52 PM
public float damping;
Quaternion rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
This is took from the old standard assets SmoothLookAt
Yes, but what if i want to rotate so that my Left side is facing the other object.
$$anonymous$$ake both sides Transform variables and reference them like so
Quaternion leftSideRotation = Quaternion.LookRotation(target.position - leftSide.position);
Quaternion rightSideRotation = Quaternion.LookRotation(target.position - rightSide.position);
leftSide.rotation = Quaternion.Slerp(leftSide.rotation, leftSideRotation, Time.deltaTime * damping);
rightSide.rotation = Quaternion.Slerp(rightSide.rotation, rightSideRotation, Time.deltaTime * damping);
Answer by highpockets · Apr 22, 2019 at 10:35 PM
You should never set the directional vectors of a transform, you will get very strange results sometimes because setting transform.right does not necessarily mean that transform.forward or transform.up will end up where you want them.
You should get the axis to rotate first (if transform.right is exactly 180 degrees away from direction, you will have to rotate just a smidge for this to work) :
if(-transform.right == direction){
transform.Rotate(0, 0.1f, 0); //rotate a smidge on the y axis to get less than 180 degrees
}
Vector3 axis = Vector3.Cross( transform.right, direction );
Now get your angle:
float angle = Mathf.Sqrt(Vector3.Dot(direction, direction) * Vector3.Dot(transform.right, transform.right)) + Vector3.Dot(direction, transform.right);
Now create your quaternion:
Quaternion newRot = new Quaternion(axis.x, axis.y, axis.z, angle).normalized;
Now we get our target rotation based on this new rotation we need to apply to our existing rotation:
Quaternion targetRotation = newRot * transform.rotation;
Now apply that to slerp:
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, timer);
timer = timer + Time.deltaTime;
That should work for you.
Cheers
Your answer
Follow this Question
Related Questions
LookRotation Vector3 is Zero, Yet Slerp Still Rotates? 2 Answers
Rotating about and only one axis 1 Answer
Need help with rotation 4 Answers
Basic AI Locked Axis 1 Answer