Skip to content

Instantly share code, notes, and snippets.

@gekidoslair
Created April 1, 2024 17:59
Show Gist options
  • Save gekidoslair/fdab4c6a25c24be6bd36e894082edbad to your computer and use it in GitHub Desktop.
Save gekidoslair/fdab4c6a25c24be6bd36e894082edbad to your computer and use it in GitHub Desktop.
A simple Click to Move player controller using a Unity Navmesh Agent.
using UnityEngine;
using UnityEngine.AI;
namespace MegaCrush.NavmeshBaker.Sample
{
/// <summary>
/// A very simple click to move player controller
/// </summary>
[RequireComponent(typeof(NavMeshAgent))]
public class ClickToMoveController : MonoBehaviour
{
private NavMeshAgent agent;
private Vector3 movePosition;
private Camera mainCam;
private Ray ray;
private RaycastHit hit;
private float distance = 1000;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
mainCam = Camera.main;
}
private void Update()
{
if (!Input.GetMouseButtonDown(0)) return;
ray = mainCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, distance))
{
movePosition = hit.point;
}
// move the agent to the position
agent.SetDestination(movePosition);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment