Player NavMeshController
using Mirror;
using UnityEngine;
using UnityEngine.AI;
namespace Gameplay.Features.Avatars
{
public class PlayerNavMeshMovement : NetworkBehaviour
{
public NavMeshAgent Agent { get; private set; }
[Header("Movement")]
public Camera playerCamera;
[SerializeField] private LayerMask _layerMask;
void Awake()
{
Agent = GetComponent<NavMeshAgent>();
}
public override void OnStartClient()
{
if (Agent != null)
{
Agent.enabled = true;
if (!isLocalPlayer)
{
Agent.updatePosition = false;
Agent.updateRotation = false;
}
}
}
// Runs only on the server when the object spawns
public override void OnStartServer()
{
if (Agent != null) Agent.enabled = true;
}
public override void OnStartLocalPlayer()
{
playerCamera = Camera.main;
}
void Update()
{
if (!isLocalPlayer) return;
if (Input.GetMouseButtonDown(0))
{
if (Physics.Raycast(playerCamera.ScreenPointToRay(Input.mousePosition), out RaycastHit hit, 2000f, _layerMask))
{
Agent.SetDestination(hit.point);
CmdMoveToPoint(hit.point);
}
}
}
[Command]
void CmdMoveToPoint(Vector3 destination)
{
Agent.SetDestination(destination);
}
}
}