Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Continuously rotate camera between to values

Discussion in 'Scripting' started by Deleted User, Jan 7, 2022.

  1. Deleted User

    Deleted User

    Guest

    I want to simulate a security camera that loops between two points.

    I tried using Mathf.PingPong and Quaternion.Lerp, but both of them only rotate once instantly and then they stay in the position they are currently in.

    Here are some examples of what I've tried:
    Code (CSharp):
    1. private float speed = 1;
    2.  
    3.     void Start()
    4.     {
    5.         StartCoroutine(CameraRotation());
    6.     }
    7.  
    8.     IEnumerator CameraRotation()
    9.     {
    10.         Quaternion startValue = this.transform.rotation;
    11.         startValue = Quaternion.Euler(0, 15, 0);
    12.  
    13.         Quaternion endValue = this.transform.rotation;
    14.         endValue = Quaternion.Euler(0, -15, 0);
    15.  
    16.         while (true)
    17.         {
    18.             this.transform.rotation = Quaternion.Lerp(startValue, endValue, Time.deltaTime * speed);
    19.             yield return null;
    20.         }
    21.     }
    and
    Code (CSharp):
    1. private float speed = 30f;
    2.  
    3.     private void Update()
    4.     {
    5.         transform.localRotation = Quaternion.Euler(0, Mathf.PingPong(Time.deltaTime * speed, 15), 0);
    6.     }
    The camera should only rotate on the y-Axis, with 15° in each direction. This should loop not stop until the game ends.

    This is my first time posting here please tell me when I'm doing something wrong. I hope you can help me trying to figure out a way to do this.
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    You need an ever-growing number for your PingPong, not the frame time. Change it to Time.time from Time.deltaTime and it should work.
     
    Deleted User likes this.
  3. alexeu

    alexeu

    Joined:
    Jan 24, 2016
    Posts:
    257
    Deleted User likes this.
  4. Deleted User

    Deleted User

    Guest

    Thank you guys this works really well however both of these scripts reset the cameras y-Axis to 0.

    Almost all my cameras who use this code are rotated and they all reset to 0. Is there a way to keep the previous location and just ping pong from there?
     
  5. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    If I'm understanding you correctly, you can create a gimbal setup by parenting the camera to another GameObject, like this:
    CameraRig
    - Camera

    Then rotate the CameraRig as needed, and PingPong the child Camera's localRotation.
     
    Deleted User likes this.