Unity 之 代码实现物体跟随鼠标移动

举报
陈言必行 发表于 2021/08/14 00:11:44 2021/08/14
3.2k+ 0 0
【摘要】 Unity 之 代码实现物体跟随鼠标移动   相关函数 Vector3.Lerp 线性插值 C# => static Vector3 Lerp(Vector3 from, Vector3 to, float t);Vector3.MoveTpwards 移向 C# => static function MoveTowards(cu...
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);
        }
        }
       }
   
  

文章来源: czhenya.blog.csdn.net,作者:陈言必行,版权归原作者所有,如需转载,请联系作者。

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

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。