using UnityEngine;
using UnityEngine.AI;
// Use physics raycast hit from mouse click to set agent destination
[RequireComponent(typeof(NavMeshAgent))]
public class ClickToMove : MonoBehaviour
{
NavMeshAgent m_Agent;
RaycastHit m_HitInfo = new RaycastHit();
void Start()
{
m_Agent = GetComponent<NavMeshAgent>();
}
void Update()
{
if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftShift))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction, out m_HitInfo))
m_Agent.destination = m_HitInfo.point;
}
}
}
I use the code above to get the mouse event and set the agent’s destination, and the agent will move to my clicked point in an area with some manual generated navmeshlinks.
using UnityEngine;
using UnityEngine.AI;
using System.Collections;
[RequireComponent(typeof(NavMeshAgent))]
public class AgentLinkMover : MonoBehaviour
{
public AnimationCurve m_Curve = new AnimationCurve();
NavMeshAgent agent;
public float speed = 1f;
IEnumerator Start()
{
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.autoTraverseOffMeshLink = false;
while (true)
{
if (agent.isOnOffMeshLink)
{
yield return StartCoroutine(Parabola(agent, 2.0f, 0.5f));
agent.CompleteOffMeshLink();
}
yield return null;
}
}
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
agent.autoTraverseOffMeshLink = false;
}
private void Update()
{
agent.speed = speed;
}
IEnumerator Parabola(NavMeshAgent agent, float height, float duration)
{
OffMeshLinkData data = agent.currentOffMeshLinkData;
Vector3 startPos = agent.transform.position;
Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
float normalizedTime = 0.0f;
while (normalizedTime < 1.0f)
{
float yOffset = height * 4.0f * (normalizedTime - normalizedTime * normalizedTime);
agent.transform.position = Vector3.Lerp(startPos, endPos, normalizedTime) + yOffset * Vector3.up;
normalizedTime += Time.deltaTime / duration;
yield return null;
}
}
}
I expect that the isOnOffMeshLink becomes true exactly in the red area and agent moves as what I coded. However, the fact is that, when the agent reach the green area, it starts jumping.
Is there any way to reconize the red area?