using UnityEngine;
using System.Collections;
public class test : MonoBehaviour {
//在场景中鼠标点击地面后,角色可以移动到目标位置
private Vector3 target;
private bool isOver = true;
public float speed;
void Start () {
}
void Update () {
if(Input.GetMouseButtonDown(0))
{
print("MouseDown");
//1. 获取鼠标点击位置
//创建射线;从摄像机发射一条经过鼠标当前位置的射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//发射射线
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(ray, out hitInfo))
{
//获取碰撞点的位置
if (hitInfo.collider.name == "Plane")
{
target = hitInfo.point;
target.y = 0.5f;
isOver = false;
}
}
//RaycastHit[] hitAll = Physics.RaycastAll(ray, 1000);
//foreach(RaycastHit hitInfo in hitAll)
//{
// print(hitInfo.collider.name);
// if (hitInfo.collider.name == "Plane")
// {
// 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;
}
}
}
}