So my friend is good at math and we attempted to write up this AI NPC movement code to move the zombies around in my game (Including pathfinding and wandering). I worked out all of the code errors so it runs but it does not do anything yet. I looked at the Hello tutorials for the Update Loop and based what I did on that. I have done other research but I haven’t found anything very helpful to me. I put the following code in the Update Loop:
[java] //Move zombies
if (Math.sqrt(Math.pow((player.getPhysicsLocation().x - zombieNode.getChild(“Zombie1”).getLocalTranslation().x),2)+Math.pow((player.getPhysicsLocation().y -zombieNode.getChild(“Zombie1”).getLocalTranslation().y),2)+Math.pow((player.getPhysicsLocation().z-zombieNode.getChild(“Zombie1”).getLocalTranslation().z),2)) < 50) //distance formula (plug in whatever number for 50)
{
//Pathfind
double direction = (-(Math.toDegrees(Math.atan((player.getPhysicsLocation().z -zombieNode.getChild(“Zombie1”).getLocalTranslation().z)/(player.getPhysicsLocation().x-zombieNode.getChild(“Zombie1”).getLocalTranslation().x)))));
pathfindX += (int) (2 * Math.cos(Math.toRadians(direction)));
pathfindZ += 2 * Math.sin(Math.toRadians(direction));
zombieNode.getChild(“Zombie1”).move(pathfindX * tpf, 0, pathfindZ * tpf);
} else {
//Wander
int xLocation;
int zLocation;
xLocation = -512 + (int)(Math.random() * ((512 - -512) + 1));
zLocation = -512 + (int)(Math.random() * ((512 - -512) + 1));
for (double i = Math.random() * 500 + 100; i > 0; i -= 1)
{
int direction = (int)(-(Math.toDegrees(Math.atan((zLocation-zombieNode.getChild(“Zombie1”).getLocalTranslation().z)/(xLocation-zombieNode.getChild(“Zombie1”).getLocalTranslation().x))))+ Math.random() * 90 - 45);
wanderX += 2Math.cos(Math.toRadians(direction));
wanderZ += 2Math.sin(Math.toRadians(direction));
zombieNode.getChild(“Zombie1”).move(wanderX * tpf, 0,wanderZ * tpf);
}
}[/java]
I would appreciate some help reviewing the code but first I’ll explain the way it is supposed to work.
First, the code gets the distance between the player and the zombie using x and z coordinates. If it is less than 50 wu away, it will pathfind. If the player is more than 50 wu away, it will wander. While pathfinding, the zombie gets the player’s position and moves towards it. While wandering, a random position is chosen and the zombie wanders towards it.
These are a few things that I think could be wrong: One, I may not be accessing the positions of the player and the zombie the correct way. Two, the equations themselves may not be working right. Three, I may not be moving the zombie in the correct way (.move).
If there is anything you could suggest adding to the code that would be wonderful.