Firstborn/Assets/RPG Creation Kit/Scripts/AI/AI Scripts/AgentLinkMover.cs

101 lines
3.6 KiB
C#
Raw Permalink Normal View History

using UnityEngine;
using UnityEngine.AI;
using System.Collections;
using RPGCreationKit.AI;
public enum OffMeshLinkMoveMethod
{
Teleport,
NormalSpeed,
Parabola,
Curve
}
[RequireComponent(typeof(NavMeshAgent))]
public class AgentLinkMover : MonoBehaviour
{
public AIMovements AI;
public bool chaseTarget = true;
public bool rotateToFaceTarget = true;
public OffMeshLinkMoveMethod m_Method = OffMeshLinkMoveMethod.NormalSpeed;
public AnimationCurve m_Curve = new AnimationCurve();
IEnumerator Start()
{
NavMeshAgent agent = GetComponent<NavMeshAgent>();
agent.autoTraverseOffMeshLink = false;
while (true)
{
if (agent.isOnOffMeshLink)
{
if (m_Method == OffMeshLinkMoveMethod.NormalSpeed)
yield return StartCoroutine(NormalSpeed(agent));
else if (m_Method == OffMeshLinkMoveMethod.Parabola)
yield return StartCoroutine(Parabola(agent, 2.0f, 0.5f));
else if (m_Method == OffMeshLinkMoveMethod.Curve)
yield return StartCoroutine(Curve(agent, 0.5f));
agent.CompleteOffMeshLink();
}
yield return null;
}
}
IEnumerator NormalSpeed(NavMeshAgent agent)
{
OffMeshLinkData data = agent.currentOffMeshLinkData;
Vector3 endPos = data.endPos + Vector3.up * agent.baseOffset;
while (agent.transform.position != endPos)
{
if (chaseTarget && AI.mainTarget != null)
{
Vector3 chasingVector = Vector3.MoveTowards(agent.transform.position, AI.mainTarget.position, agent.speed * Time.deltaTime);
chasingVector.y = agent.transform.position.y;
agent.transform.position = chasingVector;
}
else
{
agent.transform.position = Vector3.MoveTowards(agent.transform.position, endPos, agent.speed * Time.deltaTime);
}
if(rotateToFaceTarget && AI.mainTarget != null)
agent.transform.rotation = Quaternion.RotateTowards(
agent.transform.rotation,
Quaternion.LookRotation(transform.position - AI.mainTarget.position),
Time.deltaTime * 5f);
yield return null;
}
}
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;
}
}
IEnumerator Curve(NavMeshAgent agent, 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 = m_Curve.Evaluate(normalizedTime);
agent.transform.position = Vector3.Lerp(startPos, endPos, normalizedTime) + yOffset * Vector3.up;
normalizedTime += Time.deltaTime / duration;
yield return null;
}
}
}