Created
April 1, 2024 17:59
-
-
Save gekidoslair/fdab4c6a25c24be6bd36e894082edbad to your computer and use it in GitHub Desktop.
A simple Click to Move player controller using a Unity Navmesh Agent.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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