Reputation: 557
I got a problem in a game with javascript :
I've a pathfinding algorithm that hold in an array positions from the beginning point to the destination. One div have to follow that positions, and I've got an image associated to this div, which have to follow it. The problem is that the div is moving too fast for the image, so it's placing bad.
I'm searching for a method to say to this div that if the image is not arrived to that div position, so the div can't take immediately the next position, it have to wait.
I wrote this :
if (!(destX == player.x && destY == player.y)) {
var path = grid.find(player.x / 40, player.y / 40, destX / 40, destY / 40);
for (var i = 0; i < path.length; i++) {
// If the image has arrived to the div position, function continue
if (player.image.x == player.x && player.image.y == player.y) {
player.x = path[i].position.x * 40;
player.y = path[i].position.y * 40;
}
}
}
... but it's not working, because when the condition is not matching, the for loop goes to the next 'i' index...
Thanks for help !
EDIT : I would make some precisions, the function is inside a update loop :
Player.prototype.getMouseMove = function() {
$(".tile, .target").mouseup(function() {
var destX = Math.round($(this).position().left);
var destY = Math.round($(this).position().top);
if (!(destX == player.x && destY == player.y)) {
var path = grid.find(player.x / 40, player.y / 40, destX / 40, destY / 40);
for (var i = 0; i < path.length; i++) {
console.log(i);
if (player.image.x == player.x && player.image.y == player.y) {
player.x = path[i].position.x * 40;
player.y = path[i].position.y * 40;
}
else i--;
}
}
});
}
Upvotes: 0
Views: 29
Reputation: 36703
Just modify it a bit
for (var i = 0; i < path.length; i++) {
// If the image has arrived to the div position, function continue
if (player.image.x == player.x && player.image.y == player.y) {
player.x = path[i].position.x * 40;
player.y = path[i].position.y * 40;
}
else i--; // It wont increase your i if condition is not satisfied.
}
Upvotes: 1