private Vector3 targetVector3;
private float movespeed=0.5f;
private bool IsOver = true;
private GameObject player;
private Camera firstCamera;
float sensitivityX = 2f;
public void Start (GameObject _player,Camera cam)
{
player = _player;
firstCamera = cam;
}
public void Update () {
if (Input.GetMouseButton(0))
{
if (firstCamera == null)
return;
//视角移动
firstCamera.transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
//1. 获取鼠标点击位置
//创建射线;从摄像机发射一条经过鼠标当前位置的射线
Ray ray = firstCamera.ScreenPointToRay(Input.mousePosition);
//发射射线
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(ray, out hitInfo))
{
//获取碰撞点的位置
if (hitInfo.collider.name == "Ground")
{
Debug.LogError(hitInfo.collider.name);
targetVector3 = hitInfo.point;
targetVector3.y = -0.5f;
IsOver = false;
}
Debug.DrawLine(ray.origin, hitInfo.point, Color.red);
}
//2. 让角色移动到目标位置
MoveTo(targetVector3);
}
}
//让角色移动到目标位置
private void MoveTo(Vector3 tar)
{
if (!IsOver)
{
Vector3 offSet = tar - player.transform.position;
player.transform.position += offSet.normalized * movespeed * Time.deltaTime;
if (Vector3.Distance(tar, player.transform.position) < 0.5f)
{
IsOver = true;
player.transform.position = tar;
}
}
}