The simplest code to realize the reciprocating movement and rotation of objects.

To realize the reciprocating movement and rotation of props or platforms, the code is taken from Unity official content.

 

(1) Reciprocating movement of objects

using UnityEngine;
using System.Collections;

namespace HighlightingSystem.Demo
{
	public class MovementController : MonoBehaviour
	{
		public bool moveX;
		public bool moveY;
		public bool moveZ;

		public float speed = 1.2f;
		
		public Vector3 amplitude = Vector3.one;
		
		private Transform tr;
		private float counter;
		private Vector3 initialOffsets;
		
		void Awake()
		{
			tr = GetComponent<Transform>();
			initialOffsets = tr.position;
			counter = 0f;
		}
		
		void Update()
		{
			counter += Time.deltaTime * speed;
			
			Vector3 newPosition = new Vector3
			(
				moveX ? initialOffsets.x + amplitude.x * Mathf.Sin(counter) : initialOffsets.x, 
				moveY ? initialOffsets.y + amplitude.y * Mathf.Sin(counter) : initialOffsets.y, 
				moveZ ? initialOffsets.z + amplitude.z * Mathf.Sin(counter) : initialOffsets.z
			);
			
			tr.position = newPosition;
		}
	}
}

(2) The rotation of the object

using UnityEngine;
using System.Collections;

namespace HighlightingSystem.Demo
{
	public class RotationController : MonoBehaviour
	{
		public float speedX = 20f;
		public float speedY = 40f;
		public float speedZ = 80f;
		
		private Transform tr;

		void Awake()
		{
			tr = GetComponent<Transform>();
		}

		void Update()
		{
			tr.Rotate(speedX * Time.deltaTime, speedY * Time.deltaTime, speedZ * Time.deltaTime);
		}
	}
}

 

Guess you like

Origin blog.csdn.net/qq_33528212/article/details/113051424