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

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 *