[Unity3D]检测鼠标点击角色移动

发布时间 2023-11-15 18:53:05作者: 我有在努力学

学习工具
Unity3D


学习内容
如何检测鼠标点击移动角色


自己的理解
原理:通过检测鼠标的光线投射(Raycast)是否与地面碰撞(RaycastHit),再检测鼠标左键(Input.GetMouseButton(0))是否点击,如果两个都符合则执行移动方法
源代码如下:

private bool InteractWithMovement()
{
  RaycastHit hit;
  bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
  if( hasHit )
  {
    if( Input.GetMouseButton(0))
    {
      GetComponent<Mover>().StartMoveAction(hit.point);
    }
  }
}