Hello, i’ve been trying to implement pathfinding for monsters in my game. But yet i still fail to do it.
public void onWalk(float deltaTime) {
if (toPosition.equals(position)) {
toPosition.set(getNextPosition(direction, position));
return;
}
if (position.dst(toPosition) <= 0.1f) {
position.set(toPosition);
isMoving = false;
return;
}
switch (direction) {
case NORTH:
position.y += speed * deltaTime;
break;
case EAST:
position.x += speed * deltaTime;
break;
case SOUTH:
position.y -= speed * deltaTime;
break;
case WEST:
position.x -= speed * deltaTime;
break;
default:
break;
}
}
public Vector2 getNextPosition(Direction dir, Vector2 pos) {
pos = new Vector2(pos.x, pos.y);
switch (dir) {
case NORTH:
pos.y++;
break;
case EAST:
pos.x++;
break;
case SOUTH:
pos.y--;
break;
case WEST:
pos.x--;
break;
default:
break;
}
if (!world.isValidTile(pos)) {
isMoving = false;
return position;
}
return pos;
}
public void onThink(float deltaTime) {
lastWalkTime += deltaTime;
if (lastWalkTime >= 1f) {
followCreature(deltaTime);
lastWalkTime = 0f;
}
}
private void followCreature(float deltaTime) {
if (attackedCreature == null) {
return;
}
IntArray path = astar.getPath((int) position.x, (int) position.y, (int) attackedCreature.position.x, (int) attackedCreature.position.y);
for (int i = 0, n = path.size; i < n; i += 2) {
int x = path.get(i);
int y = path.get(i + 1);
position.set(x, y);
}
}
Now it looks like the monster is jumping one tile of the time, until it lands on the target. I would like it to move as a grid walking towards the target.
I use this: https://gist.github.com/NathanSweet/7587981