- Home /
how to make the camera rotate each turn
I'm trying to make the camera rotate for each players turn in a chess game, but when I made this code, the camera would stop moving. Anyone know the solution.
public void RotateCamera()
{
int x = 0;
if (isWhiteTurn == true)
{
transform.Rotate(0, 0, 0);
}
else
{
while(x < 180)
{
transform.Rotate(0, x, 0);
x++;
if(x >= 180)
{
break;
}
}
}
}
This code is execute where? Inside of a Update or inside a coroutine?
Answer by tiggy02 · Sep 20, 2016 at 06:04 AM
Dear masonb21.
The problem is that since you executed this is Update and you set the value of x to 0 in the function every frame you set x to 0. The solution is to declare x in a Start or Awake function.
Hope this works, tiggy02.
Answer by OutOfRam · Sep 20, 2016 at 02:45 AM
The problem is that you are using a while loop rather than a coroutine. A while loop will run every iteration of itself in a single frame. In other words, if you have a while loop that runs 180 times, all 180 loops will be calculated and done in a single frame. a coroutine on the other hand can be made to run a single iteration once every frame, or what ever time interval you want. Try something like this (i don't have unity near me, so it may not be perfect)
private IEnumorator Rotate()
{
int x = 0;
if (isWhiteTurn == true)
{
transform.Rotate(0, 0, 0);
yield return null;
}
else
{
while(x < 180)
{
transform.Rotate(0, x, 0);
x++;
yield return WaitForSeconds(AmountOfTimeBeforeNextLoop);
}
}
}
you are going to want to start the coroutine using
StartCoroutine("Rotate"); // Rather than Rotate()
I hope this helps
Answer by felipin · Sep 20, 2016 at 06:06 AM
Try the code below buddy
public bool isWhiteTurn;
public float rotationSpeed;
public void RotateCamera ()
{
Quaternion targetRotation = Quaternion.Euler (0, isWhiteTurn ? 0 : 180, 0);
transform.rotation = Quaternion.Lerp (transform.rotation, targetRotation,
Time.deltaTime * rotationSpeed);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612093046im_/https://answers.unity.com/themes/thub/images/avi.jpg)