- Home /
Question by
Medusa-Zenovka · Apr 26, 2015 at 09:47 PM ·
scripting problemnavmeshnavmeshagent
Mesh as Navmesh?
Is it possible to use a mesh of a moveable object (e.g. platform, spaceship) as navmesh? All I need is a way to put a mesh into an array of local positions so child objects can move like they would on a baked navmesh. I would like to use unitys NavMeshAgent if possible.
Comment
Answer by termway · Apr 27, 2015 at 11:39 AM
Sadly navmesh are limited, so I don't think it's possible right now. But as a workaround you can apply a translation offset to the renderer of your navmesh agent. Here the code I used for my agents on a moving boat using navmesh. The code below manage only one moving platform and modification are required to a more advance navigation.
//Put on your moving platform
public class NavMeshDynamic : MonoBehaviour
{
protected Vector3 initialPosition;
protected Quaternion initialRotation;
// Use this for initialization
void Awake ()
{
initialPosition = transform.position;
initialRotation = transform.rotation;
}
public Vector3 getOffsetPosition()
{
return transform.position - initialPosition;
}
public Quaternion getOffsetRotation()
{
return transform.rotation * Quaternion.Inverse(initialRotation);
}
public Vector3 getCorrectedPosition(Vector3 position)
{
return position + (transform.position - initialPosition);
}
public Quaternion getCorrectedRotation(Quaternion rotation)
{
return rotation * transform.rotation * Quaternion.Inverse(initialRotation);
}
public Vector3 getInitialPosition()
{
return initialPosition;
}
public Quaternion getInitialRotation()
{
return initialRotation;
}
}
//Put on your renderer (should be child of your navmesh agent)
public class NavMeshOffset : MonoBehaviour
{
public NavMeshDynamic navMeshDynamic;
public GameObject objectToMove;
protected Quaternion initialObjectRotation;
void Awake()
{
initialObjectRotation = objectToMove.transform.rotation;
}
void LateUpdate()
{
//Correct position from object rotation
Vector3 offsetDirection = objectToMove.transform.position - navMeshDynamic.getInitialPosition();
Vector3 offsetDirectionRotated = navMeshDynamic.getOffsetRotation() * offsetDirection;
transform.position = navMeshDynamic.transform.position + offsetDirectionRotated;
transform.rotation = objectToMove.transform.rotation * navMeshDynamic.getOffsetRotation();
}
}
Here my hierachy :
boat (NavMeshDynamic)
- agent (NavMeshAgent)
- offset (NavMeshOffset: objectToMove : agent)
rig
skinrenderer
- offset (NavMeshOffset: objectToMove : agent)
Hope it's help you.
Your answer