Saturday, January 2, 2016

unity - How to rotate a parent object while rotating a child object to a certain angle using coroutines


I have a semicircle like game object which I made by putting two arcs in an empty game object (SCircle) and rotating the 15° (for left arc) and -15° (for right arc) as seen below.


enter image description here


SCircle has an Orientation enum with two valuesLeft (rotates SCircle to 45°) and Right (rotates SCircle to -45°) as seen in the image below.


enter image description here


I use the following coroutine to move SCircle between orientations.


IEnumerator RotateLeftOrRight(Vector3 byAngles, float inTime)
{
Quaternion fromAngle = gameObject.transform.rotation ;
Quaternion toAngle = Quaternion.Euler (transform.eulerAngles);



if (circOrientation == Orientation.Left) {
toAngle = Quaternion.Euler (gameObject.transform.eulerAngles - byAngles);
circOrientation = Orientation.Right;

}
else if (circOrientation == Orientation.Right) {

toAngle = Quaternion.Euler (gameObject.transform.eulerAngles + byAngles);

circOrientation = Orientation.Left;
}


for(float t = 0f ; t <= 1f ; t += Time.deltaTime/inTime)
{
gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, t) ;
yield return null ;

gameObject.transform.rotation = Quaternion.Lerp(fromAngle, toAngle, 1);

}

}

I also used a very similar coroutine to move the individual arcs by 30° (in opposite directions) from say, Orientation Left, as seen below:


enter image description here


Since SCircle Coroutine is activated by a mouse click, I have the case where the individual arcs coroutine is run and before it is complete the parent SCircle coroutine is also run. In this case the arcs end up moving from Left to A, which is not the behavior I need. I would want the behavior of them ending up at B when moving from the Left. Likewise, from B, when the SCircle coroutine is run while the arcs coroutine is in progress the orientation will return to the Left.


Please note that the blue arrow represents the movement of the left Arc, the red represents the right Arc and the black represents movement of SCircle - the parent object.


How can I achieve the behavior from Left to B and from B back to Left?


enter image description here





No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...