Hey guys, i’m playing around with code for a tower defense game i’m working on…or it will be a tower defense game when i’m done. Right now, i’ve been trying to play around with pathfinding and a movement system…I did some googling and tried to implement a system that will move the sprite tile by tile to where the mouse clicks. I haven’t implemented astar or anything yet…I’m trying to get a basic movement system setup so I can move the sprite one tile at a time toward a mouse click…However, it isn’t working. If I click below or to the left of the sprite, it will move extremely fast to the tile clicked. If I click above or to the right of the sprite, nothing happens.
I’m a little embarrassed that i’m having trouble doing this. I’m still a newbie but have been putting a little more time into learning lately. I’m having a problem getting things structured correctly and figuring out things like this. I’m not sure how to turn it into a decent working movement system. Here is the code i’m having a problem with. My tiles are 32x32, when I call the moveTo() function, i’m breaking the mouse position down into tile position by dividing by 32.
public void moveTo(int px, int py) {
state = state.WALKING;
destx = px;
desty = py;
dx = px - x;
dy = py - y;
float length = (float) Math.sqrt(dx*dx+dy*dy);
dx=dx/length;
dy=dy/length;
}
public void update(float delta) {
if (state == state.WALKING) {
if (x != destx) {
x += (dx * speed) * delta;
}else{
dx = 0;
}
if (y != desty) {
y += (dy * speed) * delta;
}else{
dy = 0;
}
if (dx == 0 && dy == 0) {
state = state.IDLE;
destx = 0;
desty = 0;
}
System.out.println("x: " + x +
" y: " + y +
" dx: " + dx +
" dy: " + dy);
}
//System.out.println("X: " + x + " Y: " + y);
}