Rewriting code to use premade navmeshmovement values

Vcarma

New member
Hello, I should preface this with the code itself works as intended. That being said I was curious how I'd go about rewriting it to work with the provided speed and angular speed variables.

The script itself is a deviation of the Wander task from the Movement pack. Changed to only move within a radius of the start position.

The issue comes with the NavMeshAgent not updating its speed to the one provided in the already provided speed variable, meaning I need to set a new variable to update it in script. From what I've seen from researching the other scripts in the pack, this isn't necessary.

TLDR: works as intended, but doesnt use the provided NavMeshMovement speed variables. Would like pointers on how to fix this for consistency with other movement scripts

using UnityEngine;



namespace BehaviorDesigner.Runtime.Tasks.Movement
{

[TaskDescription("Wander in an area around a point using the Unity NavMesh.")]
[TaskCategory("Custom")]
public class WanderInArea : NavMeshMovement
{
public SharedFloat stalkSpeed = 6;

public SharedFloat m_areaRange = 15;

[Tooltip("The minimum length of time that the agent should pause at each destination")]
public SharedFloat m_MinPauseDuration = 0;

[Tooltip("The maximum length of time that the agent should pause at each destination (zero to disable)")]
public SharedFloat m_MaxPauseDuration = 0;

private float m_PauseTime;
private float m_DestinationReachTime;

private Vector3 startPos;

public override void OnStart()
{
startPos = transform.position;

}


public override TaskStatus OnUpdate()
{
if (HasArrived())
{
// The agent should pause at the destination only if the max pause duration is greater than 0
if (m_MaxPauseDuration.Value > 0)
{
UnityEngine.AI.NavMeshAgent agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
agent.speed = stalkSpeed.Value;

if (m_DestinationReachTime == -1)
{
m_DestinationReachTime = Time.time;
m_PauseTime = Random.Range(m_MinPauseDuration.Value, m_MaxPauseDuration.Value);
}
else if (m_DestinationReachTime + m_PauseTime <= Time.time)
{
// Only reset the time if a destination has been set.
if (Vector3.Distance(transform.position, RandomNavmeshLocation(m_areaRange.Value)) < 11)
{
SetDestination(RandomNavmeshLocation(m_areaRange.Value));
m_DestinationReachTime = -1;
}
}
}
else
{
SetDestination(RandomNavmeshLocation(m_areaRange.Value));
}
}
return TaskStatus.Running;
}

public Vector3 RandomNavmeshLocation(float radius)
{
Vector3 randomDirection = Random.insideUnitSphere * radius;
UnityEngine.AI.NavMeshHit hit;
Vector3 finalPosition = Vector3.zero;
if (UnityEngine.AI.NavMesh.SamplePosition(randomDirection, out hit, radius, 1))
{
finalPosition = hit.position;
}
return finalPosition;
}
}
}
 
Top