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

猜你喜欢

转载自blog.csdn.net/xiaochenXIHUA/article/details/83414670
今日推荐