Navmesh + Movement script for universal character object prefab...

So, I’ve come up to a kind of road block. Recently when studying basic character movement…

I realized that I had to have a mind for AI early on. What I really want to create is a single prefab that will work for all characters whose references are even stored in a list or a dictionary, and then be able to select whether these character objects are controlled or not as well as their dialogue, events and stats.

What I want to create is a single prefab that works for all NPCs, and the player prefab object won’t be separate but instead will be kind of like a ‘controlled npc’. This will allow me to set up an environment for myself in where I can create multiplayer or single player games, in where players are able to switch between controlled objects, etc…

So in starting development there were a few roadblocks that I ran into, most notably movement speed. Since I was using transform.Translate() I had a hard time getting track of what the speed was, and I was using 2D characters with frames that cycle through for animation (using 2.5D), so I needed to know what the rigidbody magnitude or velocity.z was so that I knew when to cycle the animation, either that or create a custom move speed with transform.Translate().

Recently, though, I’ve switched from using transform.Translate(), and now I’m moving to using a navmesh agent. As of right now I’m having a little bit of a hard time wrapping my head around this…So, a navmesh agent comes with it’s own speed? I’m guessing what I’m wanting to do then is to throw input to the navmesh agents way of moving an object so that the speed will translate from npc <> player seemlessly.

Has anyone had any problems with this?

The navmesh.Agent has a Speed property what you can change to your desire.
To figure out the speed it is travelling you could subtract the transform’s position of the previous frame and get the magnitude from that vector.

Vector3 previous;

void Update() {
 Vector3 direction = transform.position - previous;
 float mySpeed = direction.magnitude;
 previous = transform.position;
}
1 Like

Gotcha, thanks. I found the solution I was looking for and it’s pretty much exactly what you posted.

Secondly, to move the character you can do this:

if (Input.GetKey (KeyCode.W)) {
   O_moveToInputPoint = O_position + O_forward; //places input point directly forward of object
}

if (O_navMeshAgentDestUpdating == true) {
   O_navMeshAgent.destination = O_moveToInputPoint;
}

Something along those lines. Just set the nav mesh setdestination point to just in front of the object to get it to move. This is good for RPG movement, though probably not good for FPS movement, not sure. Hoping people looking for an answer to this will find this helpful.