Unity makes an object rotate along any axis of itself

Time:2021-4-18

In this paper, we share the example of unity to realize the object rotating along any axis for your reference. The specific contents are as follows

1、 Create an object that needs to be rotated

2、 Write a script to control the object

using UnityEngine;
using System.Collections;
 
public class Test_ElectricFan : MonoBehaviour 
{
 Public bool isopen = false; // start rotation
 Public int speed = 2; // speed of rotation
 
 
 // Use this for initialization
 void Start () 
 {
 
 }
 
 // Update is called once per frame
 void Update () 
 {
 if(isOpen)
 {
 
  RotateAxisOfSelf(SelfAxis.Y,speed);
 }
 
 }
 
 /// <summary>
 ///Make an object rotate about its axis
 /// </summary>
 ///< param name = "axisx" > own axis < / param >
 private void RotateAxisOfSelf(SelfAxis selfAxis,int speed=2)
 {
 switch(selfAxis)
 {
 case SelfAxis.X:
  this.transform.Rotate (new Vector3(1*Time.deltaTime*speed,0,0));
  break;
 case SelfAxis.Y:
  this.transform.Rotate (new Vector3(0,1*Time.deltaTime*speed,0));
  break;
 case SelfAxis.Z:
  this.transform.Rotate (new Vector3(0,0,1*Time.deltaTime*speed));
  break;
 default:
  this.transform.Rotate (new Vector3(1*Time.deltaTime*speed,0,0));
  break;
 
 }
 
  
 } 
 
 
 //Enumeration axis
 enum SelfAxis
 {
 X,
 Y,
 Z,
 
 }
 
}

3、 Add the prepared script to the object that needs to rotate along any axis of itself, then run the program, and then click open to check. At this time, the object begins to rotate

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.