- Home /
Rotating to 180 degrees and back to 0
I've been looking to create some functionality that flips a 2D Camera 180 degrees in the Z axis. To do this I've made the main camera the Child of a "CameraAnchor" Empty GO and have then been referencing it on a script.
The Setup for that Script is
public Rigidbody2D rb;
public GameObject cameraAnchor;
public bool flipped = false;
public float rotateSpeed = 5f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
cameraAnchor = GameObject.FindGameObjectWithTag("Anchor");
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
flipped = !flipped;
}
if (flipped)
{
rb.gravityScale = -1.75f;
StartCoroutine(RotateCamera());
}
else
{
rb.gravityScale = 1.75f;
StartCoroutine(RotateCameraBack());
}
}
So, the update function calls a Coroutine when the flipped bool is true, which happens after pressing the key. This first Coroutine to flip the camera 180 degrees which is below works exactly as I want it to
IEnumerator RotateCamera()
{
float moveSpeed = 1f;
while (cameraAnchor.transform.rotation.z < 180)
{
cameraAnchor.transform.rotation = Quaternion.Lerp(cameraAnchor.transform.rotation, Quaternion.Euler(0, 0, 180), moveSpeed * Time.deltaTime);
yield return null;
}
cameraAnchor.transform.rotation = Quaternion.Euler(0, 0, 180);
yield return null;
}
Once the button is pressed again this should rotate back to 0. I used an adaption of the same coroutine thinking this would work but it appears to be sticking in the while loop. I'm suspecting something about it not reaching zero correctly. As I understand it the code below should be rotating to a target of -180 over a time set by multiplying my float against delta time, but I'm clearly wrong about that.
IEnumerator RotateCameraBack()
{
float moveSpeed = 1f;
while (cameraAnchor.transform.rotation.z > 0)
{
cameraAnchor.transform.rotation = Quaternion.Lerp(cameraAnchor.transform.rotation, Quaternion.Euler(0, 0, -180), moveSpeed * Time.deltaTime);
yield return null;
}
cameraAnchor.transform.rotation = Quaternion.Euler(0, 0, 0);
yield return null;
}
Any suggestions as to why I'm getting odd results and some further explanation about the head melting logic that is quaternions would be very much appreciated
Your answer
Follow this Question
Related Questions
need help regarding rotating arm 0 Answers
Finding the angle between 2 clicked points 2 Answers
The best way for working with rotation in 2d game 1 Answer
What causes this object to re-rotate itself after it hits it's destination? 1 Answer
follow an object's x-axis and have it translate smoothly into another object's z-axis rotation 1 Answer