Unity获取鼠标点击位置,物体朝鼠标点击处移动
大型游戏中经常会有这种场景,点击屏幕位置,人物就会朝着鼠标点击位置移动,下面我们就来实现这种效果。
首先,我们在场景中添加一个Plane,并且设置它的tag为Plane,然后,在Plane上面添加一个Cube,设置好位置,刚好放置在Plane上面,最后,给cube添加一个脚本,脚本内容如下:
using UnityEngine;
using System.Collections;
public class RayCastTest : MonoBehaviour {
//cube移动速度
public float speed = 3f;
private Vector3 offsetVec;
// Update is called once per frame
void Update () {
RaycastHit hitInfo;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hitInfo, 100))
{
//当射线碰撞到plane并且鼠标左键按下时
if(hitInfo.transform.tag == "Plane" && Input.GetMouseButtonDown(0))
{
//让cube方向朝向点击位置
transform.LookAt(hitInfo.point);
offsetVec = hitInfo.point - transform.position;
}
}
//向量的magnitude表示这个向量的长度,当cube离我们点击位置小于1的时候才停止移动,这个数值可以自己调节
if(offsetVec.magnitude > 1f)
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
//更新offsetVec的值
offsetVec = hitInfo.point - transform.position;
}
}
}
运行的时候可能会出现一些bug,比如说cube往前移动的时候,坐标会逐渐往下偏移,这种现象是因为点击位置的坐标比cube坐标偏下,获取到点击位置坐标的时候修改一下Y轴大小可消除这个bug。
文章来自:http://www.cnblogs.com/dearzhangle/p/4070889.html