您的位置:首页 > 移动开发 > Unity3D

unity让物体移动到鼠标点击点

2017-01-06 16:53 453 查看
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;
}
b85a
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unity 移动 鼠标