日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Unity實(shí)現(xiàn)物體跟隨鼠標(biāo)移動(dòng)_C#教程

作者:陳言必行 ? 更新時(shí)間: 2022-03-27 編程語(yǔ)言

本文實(shí)例為大家分享了Unity實(shí)現(xiàn)物體跟隨鼠標(biāo)移動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下

相關(guān)函數(shù)

Vector3.Lerp 線性插值
C# => static Vector3 Lerp(Vector3 from, Vector3 to, float t);

Vector3.MoveTpwards 移向
C# => static function MoveTowards(current: Vector3, target: Vector3, maxDistanceDelta: float): Vector3;

Vector3.SmoothDamp 平滑阻尼
C# =>static Vector3 SmoothDamp(Vector3 current, Vector3 target, Vector3 currentVelocity, float smoothTime, float maxSpeed = Mathf.Infinity, float deltaTime = Time.deltaTime);

著時(shí)間的推移,逐漸改變一個(gè)向量朝向預(yù)期的方向移動(dòng)

向量由一些像彈簧阻尼器函數(shù)平滑,這將用遠(yuǎn)不會(huì)超過(guò),最常見(jiàn)的用途是跟隨相機(jī)

實(shí)現(xiàn)跟隨鼠標(biāo)運(yùn)動(dòng)

public class Demo : MonoBehaviour {
?
? ? void Start () {
? ? }
?
? ? void Update () {
? ? ? ? // 此時(shí)的攝像機(jī)必須轉(zhuǎn)換 2D攝像機(jī) 來(lái)實(shí)現(xiàn)效果(即:攝像機(jī)屬性Projection --> Orthographic)
? ? ? ? Vector3 dis = Camera.main.ScreenToWorldPoint(Input.mousePosition); //獲取鼠標(biāo)位置并轉(zhuǎn)換成世界坐標(biāo)
? ? ? ? dis.z = this.transform.position.z; //固定z軸
? ? ? ? this.transform.position = dis; //使物體跟隨鼠標(biāo)移動(dòng)
? ? ? ? Debug.Log(dis); //輸出變化的位置
? ? ? ? //使用Lerp方法實(shí)現(xiàn) 這里的Time.deltaTime是指移動(dòng)速度可以自己添加變量方便控制
? ? ? ? this.transform.position= Vector3.Lerp(this.transform.position,dis,Time.deltaTime);
? ? ? ? //使用MoveTowards方法實(shí)現(xiàn),這個(gè)方法是勻速運(yùn)動(dòng)
? ? ? ? this.transform.position = Vector3.MoveTowards(this.transform.position, dis, Time.deltaTime);
? ? ? ? //使用SmoothDamp方式實(shí)現(xiàn),給定時(shí)間可以獲取到速度
? ? ? ? Vector3 speed = Vector3.zero;
? ? ? ? this.transform.position = Vector3.SmoothDamp(this.transform.position, dis,ref speed, 0.1f);
? ? ? ? Debug.Log(speed);
? ? }
}

根據(jù)鼠標(biāo)點(diǎn)下位置移動(dòng)物體:

public class Move : MonoBehaviour
{
? ? void Start()
? ? {
? ? ? ??
? ? }
?
? ? void Update()
? ? {
? ? ? ? if (Input.GetMouseButton(0))
? ? ? ? {
? ? ? ? ? ? //獲取需要移動(dòng)物體的世界轉(zhuǎn)屏幕坐標(biāo)
? ? ? ? ? ? Vector3 screenPos = Camera.main.WorldToScreenPoint(this.transform.position);
? ? ? ? ? ? //獲取鼠標(biāo)位置
? ? ? ? ? ? Vector3 mousePos = Input.mousePosition;
? ? ? ? ? ? //因?yàn)槭髽?biāo)只有X,Y軸,所以要賦予給鼠標(biāo)Z軸
? ? ? ? ? ? mousePos.z = screenPos.z;
? ? ? ? ? ? //把鼠標(biāo)的屏幕坐標(biāo)轉(zhuǎn)換成世界坐標(biāo)
? ? ? ? ? ? Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos);
? ? ? ? ? ? //控制物體移動(dòng)
? ? ? ? ? ? transform.position = worldPos;
? ? ? ? ? ? //剛體的方式
? ? ? ? ? ? //transform.GetComponent<Rigidbody>().MovePosition(worldPos);
? ? ? ? }
? ? }
}

原文鏈接:https://czhenya.blog.csdn.net/article/details/76615325

欄目分類
最近更新