C# script to make GameObject rotate between given angles at given speed.

Content not available.
Please allow cookies by clicking Accept on the banner

Updated Script:

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

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

//Rotates object at given speed between given angles

public class RotateBetweenAngles : MonoBehaviour {
    [SerializeField] private Transform objectToRotate;
    [SerializeField] private bool rotateThisObject = false;

    [SerializeField] private Vector3 rotatingSpeed;
    [SerializeField] private Vector3 beginAngles;
    [SerializeField] private Vector3 endAngles;

    private Vector3 angles;

    private void Start()
    {
        angles = Vector3.zero;

        if (rotateThisObject)
        {
            objectToRotate = transform;
        }
    }

    private void Update()
    {
        if (rotatingSpeed.x != 0.0f)
        {
            angles.x = Mathf.PingPong(Time.time * rotatingSpeed.x, endAngles.x) - beginAngles.x;
        }

        if (rotatingSpeed.y != 0.0f)
        {
            angles.y = Mathf.PingPong(Time.time * rotatingSpeed.y, endAngles.y) - beginAngles.y;
        }

        if (rotatingSpeed.z != 0.0f)
        {
            angles.z = Mathf.PingPong(Time.time * rotatingSpeed.z, endAngles.z) - beginAngles.z;
        }

        objectToRotate.eulerAngles = angles;
    }
}

 

Old Script:

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

// © 2017 TheFlyingKeyboard
// theflyingkeyboard.net

public class RotateBetweenAngles : MonoBehaviour {
 public Vector3 rotatingSpeed;
 public Vector3 beginAngles;
 public Vector3 endAngles;

 private Vector3 angles;

 private void Start()
 {
 angles = Vector3.zero;
 }

 void Update()
 {
 if(rotatingSpeed.x != 0.0f)
 {
 angles.x = Mathf.PingPong(Time.time * rotatingSpeed.x, endAngles.x) - beginAngles.x;
 }
 
 if(rotatingSpeed.y != 0.0f)
 {
 angles.y = Mathf.PingPong(Time.time * rotatingSpeed.y, endAngles.y) - beginAngles.y;
 }
 
 if(rotatingSpeed.z != 0.0f)
 {
 angles.z = Mathf.PingPong(Time.time * rotatingSpeed.z, endAngles.z) - beginAngles.z;
 } 

 transform.eulerAngles = angles;
 }
}

 



Unity C# Rotate GameObject Between Angles
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close