大型游戏中经常会有这种场景,点击屏幕位置,人物就会朝着鼠标点击位置移动,下面我们就来实现这种效果。
首先,我们在场景中添加一个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