- Home /
Smoothly flipping an object on one axis on click then back again
I have been working on a way to display an object in front of the camera that could be flipped when it was clicked, the immediate application is to provide a way to flip a "card" over to reveal the reverse site.
To an extent I have got this working.
There is an issue with this however in that once it has done the initial flip from the front side to the reverse the flip back is instant.
public class SpinObjectOnClick : MonoBehaviour {
private enum CardSide
{
Front,
Back
}
private bool rotating = false;
private CardSide side = CardSide.Front;
private Quaternion initialRotation;
private Quaternion targetRotation;
public void OnMouseUp()
{
if (rotating)
return;
rotating = true;
if (side == CardSide.Front)
{
initialRotation = transform.rotation;
targetRotation = Quaternion.AngleAxis(0, Vector3.right) * Quaternion.AngleAxis(0, Vector3.up) * Quaternion.AngleAxis(0, Vector3.forward);
}
else
{
targetRotation = initialRotation;
}
}
public void Update()
{
if (!rotating)
return;
Debug.Log("Rotating " + transform.rotation.y + " End = " + targetRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 4);
// consider the card flipped over when it is so close there is no perceptable reason why not
if (transform.rotation.y - targetRotation.y < 0.001)
{
rotating = false;
side = side == CardSide.Front ? CardSide.Back : CardSide.Front;
transform.rotation = targetRotation ;
}
}
}
I am happy to accept any other comments about the code as well, this is only Day 4 of my Unity3d journey.
Answer by BinaryCaveman · Oct 24, 2010 at 09:16 PM
I think the issue is in this line:
if (transform.rotation.y - targetRotation.y < 0.001)
which conflicts with this line:
transform.rotation = targetRotation;
The difference of the rotation from when the object is rotated backwards to when the object is rotated forwards is negative. Using the if statement you wrote, it considers transform.rotation
and targetRotation
to be near, and it sets the rotation of the object to targetRotation
.
You want to change your code to this:
// Use the absolute value to change the difference to positive before checking
if (Mathf.abs(transform.rotation.y - targetRotation.y) < 0.001)