zoukankan      html  css  js  c++  java
  • Unity 鼠标点击跟随移动

     代码内容


    public class Mouse : MonoBehaviour
    {
    // Start is called before the first frame update
    void Start()
    {

    }


    // Update is called once per frame
    void Update()
    {
    AGF();

    }
    /// <summary>
    /// 跟随鼠标移动并旋转
    /// </summary>
    public void AGF()
    {
    //点击鼠标右键获取信息
    if (Input.GetMouseButton(1))
    {
    //1获得鼠标点击屏幕的二维坐标
    Vector3 mouse = Input.mousePosition;
    //2创建一个射线 从相机位置到鼠标点击的位置的方向上
    Ray ray = Camera.main.ScreenPointToRay(mouse);
    //定义一个射线检测的保存对象
    RaycastHit hit;//hit保存射线发射后碰撞的信息
    //开始碰撞检测,射线检测返回一个bool类型,true:有碰撞,false:无碰撞
    if (Physics.Raycast(ray, out hit, 100f)) //碰撞检测(射线,碰撞结果给hit,射线的长度100米)
    {
    //获取坐标信息
    print(hit.point);
    target= new Vector3(hit.point.x, 2f, hit.point.z);
    //获取旋转信息
    Vector3 dir = target - rotatepos.transform.position;
    Quaternion lookRotation = Quaternion.LookRotation(dir);
    rotation = Quaternion.Lerp(rotatepos.transform.rotation, lookRotation, 2).eulerAngles;

    }
    }

    //判断是否有信息 有就执行
    else if (target!=null)
    {
    //判断目标旋转值和自己旋转值是否一致 不一致就执行
    if (rotation.y != rotatepos.transform.localEulerAngles.y)
    {
    float value = Mathf.MoveTowards(rotatepos.transform.localEulerAngles.y, rotation.y, 3);
    rotatepos.transform.rotation = Quaternion.Euler(Zvalue, value, 0f);
    }
    print(rotation.y);
    print(rotatepos.transform.localEulerAngles.y);
    //移动自己向目标点移动
    transform.position = Vector3.MoveTowards(transform.position, target, 0.2f);
    }

    }
    public float Zvalue = 90;
    public Vector3 target;
    public GameObject rotatepos;
    private Vector3 rotation;
    }

    鼠标跟随的步骤   

    获取鼠标屏幕上的坐标

    转换屏幕坐标成世界坐标

    获取3D坐标

    获取3D旋转

    判断是否执行信息

    执行移动到目标点

    执行朝向目标点

    其他的就是一些代码执行顺序产生的效果

    效果图

     

     

     移动目标点

    朝向目标点

  • 相关阅读:
    IIS7中的几种身份鉴别方式(一)Basic身份验证
    IIS7中的几种身份鉴别方式(二)集成身份验证
    java集合
    SharePoint 2010中welcome page的设置细节
    SharePoint中使用Linq出现未将对象引用到实例化的解决方法
    SharePoint 2010中关于An error was encountered while retrieving the user profile的处理方式记录
    The Need for an Architectural Body of Knowledge
    The Softer Side of the Architect
    Event Receivers 学习小结
    使用SmtpClient发送带图片的邮件的代码实现
  • 原文地址:https://www.cnblogs.com/suiyi78/p/13866884.html
Copyright © 2011-2022 走看看