最简单的代码,实现物体的往复移动和旋转。

实现例如道具或者平台的往复移动和旋转,代码取自Unity官方内容。

(1)物体的往复移动

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)物体的旋转

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);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_33528212/article/details/113051424