Camera脚本:
1 << 8 指的是检测射线层级Layer为第8个
using UnityEngine;
public class PlayerController : MonoBehaviour
{
// 主角
public Player currentPlayer;
private RaycastHit raycastHit;
void Update()
{
if(Input.GetMouseButtonDown(0))
{
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out raycastHit, 1000, 1 << 8))
{
if (currentPlayer != null)
{
currentPlayer.MoveToTarget(raycastHit.point);
}
}
}
}
}
角色脚本:
using UnityEngine;
using UnityEngine.AI;
public class Player : MonoBehaviour
{
// 寻路组件
private NavMeshAgent agent;
void Start()
{
agent = transform.GetComponent<NavMeshAgent>();
if (agent == null)
{
Debug.LogError("NavMeshAgent Is Null");
}
}
public void MoveToTarget(Vector3 targetPos)
{
agent.SetDestination(targetPos);
}
}