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

學無先后,達者為師

網站首頁 編程語言 正文

Unity實現物體跟隨鼠標移動_C#教程

作者:陳言必行 ? 更新時間: 2022-03-27 編程語言

本文實例為大家分享了Unity實現物體跟隨鼠標移動的具體代碼,供大家參考,具體內容如下

相關函數

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

著時間的推移,逐漸改變一個向量朝向預期的方向移動

向量由一些像彈簧阻尼器函數平滑,這將用遠不會超過,最常見的用途是跟隨相機

實現跟隨鼠標運動

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

根據鼠標點下位置移動物體:

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

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

欄目分類
最近更新