1. 程式人生 > >Unity實現物體移動的通用方法

Unity實現物體移動的通用方法

一、建立需要移動的物體

二、編寫控制指令碼

using UnityEngine;
using System.Collections;

public class Test_ElectricFan : MonoBehaviour 
{
	public int speed=2;					//旋轉的速度

	Vector3 target;
	

	// Use this for initialization
	void Start () 
	{
		 target = new Vector3 (0,0,0);
	}
	
	// Update is called once per frame
	void Update () 
	{
		if(Input.GetKey(KeyCode.M))
		{
			MoveToTargetPosition(target,3);

		}

	}

	
	/// <summary>
	/// 控制物體移動的方法
	/// </summary>
	/// <param name="targetPos">Target position.</param>
	/// <param name="moveMethod">Move method.</param>
	/// <param name="speed">Speed.</param>
	private void  MoveToTargetPosition(Vector3 targetPos, int moveMethod=0,float speed=2)
	{
		float moveSpeed = speed * Time.deltaTime; 
		if(targetPos!=null&&speed>0)
		{
			switch(moveMethod)
			{
			case 0:
				//控制物體移動到目標位置
				this.transform.localPosition = Vector3.MoveTowards(this.transform.localPosition, targetPos, moveSpeed);
				break;
			case 1:
				//控制物體移動到目標位置
				this.transform.localPosition =new Vector3(Mathf.Lerp(this.transform.localPosition.x, targetPos.x, moveSpeed),Mathf.Lerp(this.transform.localPosition.y, targetPos.y, moveSpeed),Mathf.Lerp(this.transform.localPosition.z, targetPos.z, moveSpeed));
				break;
			case 2:
				//控制物體向前、後、左、右移動
				this.transform.Translate(Vector3.forward * moveSpeed);
				this.transform.Translate(Vector3.right * moveSpeed);
				break;
			case 3:
				//新增Rigibody給物體力來移動
				if(this.gameObject.GetComponent<Rigidbody>()==null)
				{
					this.gameObject.AddComponent<Rigidbody>();
				}
				this.gameObject.GetComponent<Rigidbody>().AddForce(Vector3.forward*moveSpeed, ForceMode.Impulse);

				break;
			
			default:
				this.transform.localPosition = Vector3.MoveTowards(this.transform.localPosition, targetPos, moveSpeed);
				break;
				
			}

		}

	}



	

}

三、新增該控制指令碼到需要移動的物體上,然後執行程式,按著“M”鍵則物體移動

 

參考:https://blog.csdn.net/lcy0221/article/details/44040739

          https://www.jianshu.com/p/12f656c29a36