Skip to content

Instantly share code, notes, and snippets.

@tiagosr
Last active August 23, 2019 20:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagosr/e1e7e1bd7508472391532418b7b09d13 to your computer and use it in GitHub Desktop.
Save tiagosr/e1e7e1bd7508472391532418b7b09d13 to your computer and use it in GitHub Desktop.
Navmesh-using movement pseudocode
/*
This code works well for an ostensibly-static world in Unity, to avoid doing raycasts or anything similar.
Might need some adjustment to the specifics of how it currently works in Unity or your scene
(and this was written without proper checking, but it's informed pseudocode)
*/
Vector3[] current_move_path = null;
int current_move_path_index = 0;
...
// movement code
bool needsWalk = true;
while (needsWalk) {
if (current_move_path) {
if (current_move_path_index >= current_move_path.Length) {
float remaining = speed * Time.deltaTime;
Vector3 current_move_to = transform.position; // location of the player
for(int i = current_move_path_index; i < current_move_path.Length; i++) {
// test how much we need to walk in the current section of the path
remaining -= Vector3.distance(current_move_to, current_move_path[i]);
// current section is less than what remains to walk
if (remaining >= 0.0) {
// set the location for the next query to the path
current_move_to = current_move_path[i];
current_move_path_index = i+1;
} else {
Vector3 direction = current_move_path[i] - current_move_to;
float total_distance = direction.magnitude;
if (total_distance > 0.0f) { // avoid divide by zero here
// remaining is negative here, so it will cut down on total_distance
direction *= (total_distance+remaining)/total_distance;
current_move_to += direction; // add up the remaining section of the walk
}
}
}
transform.position = current_move_to;
} else {
current_move_path = null;
}
}
needsWalk = false;
if (!current_move_path) { // we might have set current_movie_path to null in the condition before
// calculate the next piece of the path here
...
AI.NavMeshPath path;
if (agent.CalculatePath(transform.position + (direction * speed * Time.deltaTime), path)) {
if (path.status != AI.NavMeshPathStatus.PathInvalid) {
current_move_path = path.corners;
current_move_path_index = 0;
needsWalk = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment