[Unity&RPG]实现简单的鼠标点击移动 角色
unity 5.6
该场景所用 必备 的物体:
Cube: GameObject--3D Object--Cube
Canvas: GameObject--UI--Canvas
GameObject: GameObject--Create Empty
GameObject 物体 的组件如下所示
创建 Plane: GameObject--3D Object--Plane
Navigation 窗口:Windows -- Navigation
烘培Plane
Navigation视图Object,Scene Filter:选择All
勾选 Navigation Static
选中Plane物体,Navigation视图Bake,进行烘培。烘培成功,对应 的物体 就会 如下图所示。
WorldInteraction.cs 的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldInteraction : MonoBehaviour {
public UnityEngine.AI.NavMeshAgent playerAgent;//网格代理组件对象 玩家代理
// Update is called once per frame 每一帧进行更新
void Update () {
if (Input.GetMouseButtonDown(0)&& !UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
{
GetInteraction();
}
}
private void GetInteraction()
{//朝鼠标点击的 位置 发射一条射线
Ray interactionRay = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);//场景中必须含有 Canvas,否则无效
RaycastHit interactionInfo;//互动物体 碰撞到的物体
if (Physics.Raycast(interactionRay, out interactionInfo, Mathf.Infinity))//发射一条3D射线
{
GameObject interactedObject = interactionInfo.collider.gameObject;//获得射线 碰撞 到的物体
if (interactedObject.tag == "Interactable Object")//判断物体 的标签
{Debug.Log("Interactable interacted");}
else
{
playerAgent.destination = interactionInfo.point;//使得 玩家 代理 的目的地 为 碰撞物体 的点
}
}
}
} WorldInteraction.cs 的截图:
参考资料:
3.
4.
5.
6.
