# Java: Basic Movement AI not working

I am working on a basic AI system to get an entity to follow a player. I created both the player and the ghost entity, but it seems as if the ghost only wants to increment both x and y, it never wants to do the opposite, or choose only x or y to use. Here is where I implemented the ghost and player in my constructor:

public MansionAzazel() {
...
TileCoordinate ghostSpawn = new TileCoordinate(52, 50);
TileCoordinate playerSpawn = new TileCoordinate(54, 52);
player = new Player(playerSpawn.x(), playerSpawn.y(), key);
player.init(level);
ghost = new Ghost(ghostSpawn.x(), ghostSpawn.y(), player);
ghost.init(level);
...
}


Here is the update() function for the ghost:

public void update() {
int xa = 0, ya = 0;
if (anim < 1000000)
anim++;
else
anim = 0;

if (player.getX() > xa)
xa++;
if (player.getX() < xa)
xa--;
if (player.getY() > ya)
ya++;
if (player.getY() < ya)
ya--;

if (xa != 0 || ya != 0) {
move(xa, ya);
walking = true;
} else
walking = false;
}


In which to sum it all up, the ghost entity will only and always move in one direction because the coordinates are 0 and I don't know why.

• What is your question? – wes Aug 12 '13 at 18:50
• It looks like your ghost update function uses player.getX() when checking for Y coordinates. You might want to fix that. Also, you should output what player.getX() and player.getY() returns in your ghost update function to see what you get. – UnderscoreZero Aug 12 '13 at 22:01
• @UnderscoreZero I said that it returns -1 for both of them. I – Shzylo Aug 12 '13 at 22:04
• What I meant was change the line System.out.println(xa + ", " + ya); to System.out.println(xa + ", " + ya + " " + player.getX() + ", " + player.getY()); – UnderscoreZero Aug 12 '13 at 22:14
• @UnderscoreZero after I changed getX to getY from checking y coordinate they both print out positive 1 Also, I divided the player.getX() and player.getY() by 16 (tile size) it prints out the actual location, just not ghost. – Shzylo Aug 12 '13 at 22:14

• Okay, @JMB you were quite right about that. It does reset the variables each time. Instead of using the my variables xa and ya I used this.getX() and this.getY() which worked perfectly! – Shzylo Aug 13 '13 at 16:16