Unity实现物体跟随鼠标移动

这篇文章主要为大家详细介绍了Unity实现物体跟随鼠标移动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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().MovePosition(worldPos);         }     } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持0133技术站。

以上就是Unity实现物体跟随鼠标移动的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程