好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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<Rigidbody>().MovePosition(worldPos); ? ? ? ? } ? ? } }

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

查看更多关于Unity实现物体跟随鼠标移动的详细内容...

  阅读:51次