//在场景中鼠标点击地面后,角色可以移动到目标位置 //把代码挂在摄像机上 //vector3 target是挂在需要移动的主角上
private Vector3 target;
private bool isOver = true;
public float speed=1f;
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
//创建射线;从摄像机发射一条经过鼠标当前位置的射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//发射射线
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(ray, out hitInfo))
{
//获取碰撞点的位置
if (hitInfo.collider.name == "Terrain")
{
target = hitInfo.point;
target.y = 0.5f;
isOver = false;
}
}
}
//2. 让角色移动到目标位置
MoveTo(target);
}
//让角色移动到目标位置
private void MoveTo(Vector3 tar)
{
if (!isOver)
{
Vector3 offSet = tar - transform.position;
transform.position += offSet.normalized * speed * Time.deltaTime;
if (Vector3.Distance(tar, transform.position) < 0.5f)
{
isOver = true;
transform.position = tar;
}
}
}
}
|