Search Unity

Bug I'm confused as to how to solve this bug

Discussion in 'Scripting' started by Copyafriend, May 31, 2023.

  1. Copyafriend

    Copyafriend

    Joined:
    Mar 19, 2023
    Posts:
    1
    I wrote a coroutine by modifying some I found online to rotate to a specific angle then stop, and it works fine going in a full loop when hitting E, but when hitting Q if it's at 0 rotation, then it starts spinning wildly and doesnt stop, this bug does not occur if at rotations -90, 180, or 90. I am extremely confused as I am a new programmer and would appreciate any advice.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class CameraRotate : MonoBehaviour
    {
    bool rotating = false;
    int rotationAngle = 90;
    [SerializeField] float rotationSpeed = 3;
    void Update()
    {

    if(Input.GetKeyDown(KeyCode.E) && !rotating){
    float targetRotation = transform.rotation.eulerAngles.y - 90f;
    StartCoroutine(Rotate90(rotationAngle, targetRotation));
    }

    if(Input.GetKeyDown(KeyCode.Q) && !rotating){
    float targetRotation = transform.rotation.eulerAngles.y + 90f;
    StartCoroutine(Rotate90(-rotationAngle, targetRotation));
    }

    }

    IEnumerator Rotate90(int Angle, float targetYRotation){
    rotating = true;
    Vector3 to = new Vector3(0, targetYRotation, 0);
    while (Vector3.Distance(transform.eulerAngles, to)>1f){

    transform.eulerAngles = Vector3.Lerp(transform.eulerAngles, to, rotationSpeed*Time.deltaTime);
    yield return new WaitForEndOfFrame();
    }

    transform.eulerAngles = to;
    rotating = false;
    }
    }