Reputation: 31
Im trying to create simple movement AI for GameObjects.
Each GameObject has NavMeshAgent
Vector3 destination = new Vector3(Random.Range(-walkArea, walkArea), 0, Random.Range(-walkArea, walkArea));
navAgent.SetDestination(destination);
That's what im trying to do. But my baked ground not flat, there could be Y axis up to 30-40.
So if there mountains around GameObject he just gets stuck and can't climb over.
What can i do about it? If i just navAgent.Move(destination)
, everything works fine. GameObject teleports on X-Z position without worrying about Y axis.
How i can do same thing but with SetDestination
?
Upvotes: 2
Views: 1783
Reputation: 856
Get the ground y
by casting a Ray
where groundLayerMask
is the LayerMask
of your ground to prevent misbehave.
public void WalkTo(Vector3 position)
{
Physics.Raycast(position + Vector3.up * 64, Vector3.down, out RaycastHit hit, 128, groundLayerMask);
position.y = hit.y;
navAgent.SetDestination(position);
}
So we cast a Ray from 64 units above the position to find the ground y and then set it manually. (The RaycastHit is struct so if there is no hit, y will be 0.)
Upvotes: 0
Reputation: 31
I found solution.
In main GameObject
i created empty gameobject
with NavMeshAgent
.
Vector3 destination = new Vector3(Random.Range(-walkArea, walkArea), 0, Random.Range(-walkArea, walkArea));
navDestinationObject.Move(destination);
navAgent.destination = navDestinationObject.transform.position;
navDestinationObject
gets right Y axis on .Move
, then we just move main GameObject
to navDestinationObject
position.
But i think there must be better solution...
Upvotes: 1