Skip to content

Instantly share code, notes, and snippets.

@bdecarne
Created November 5, 2015 18:02
Show Gist options
  • Save bdecarne/bde0ba0bdc1ba78a13b3 to your computer and use it in GitHub Desktop.
Save bdecarne/bde0ba0bdc1ba78a13b3 to your computer and use it in GitHub Desktop.
Unity : ClickToMoveNavMeshAgent
using UnityEngine;
using System.Collections;
public class ClickToMoveNavMeshAgent : MonoBehaviour {
private NavMeshAgent agent;
private Animator anim;
private object mTransform;
private Vector3 targetPosition;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent>();
agent.speed = 10f;
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
var ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
var hitInfo = new RaycastHit();
Physics.Raycast(ray, out hitInfo, 500);
targetPosition = hitInfo.point;
agent.SetDestination(targetPosition);
}
if (agent.hasPath && (transform.position - targetPosition).sqrMagnitude < 0.10)
{
agent.velocity = new Vector3();
agent.ResetPath();
}
anim.SetBool("walk", agent.hasPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment