Your problem doesn't need any path-finding. This is where vectors come in handy. For your example, you would calculate a direction vector (which is the normalized vector pointing from your player to the mouse). Then you increase the position of your sprite by direction * speed * deltaTime
or (with a fixed timestep) by direction * distanceToCoverEachUpdate
.
It's also a good idea to perform a check of the remaining distance, so if your sprite is closer to the target node than the current speed, just move the sprite by the remaining distance instead (otherwise the sprite would overshoot the target).
Update:
If your libaray/game-engine doesn't come with a vector implementation, you could use something existing, or just work with x
and y
values separately.
This would then look like this:
// Set the target position
var targetX = mouse.x;
var targetY = mouse.y;
// Get the direction in x and y (delta)
var directionX = targetX - player.x;
var directionY = targetY - player.y;
// Normalize the direction
var len = Math.sqrt(directionX * directionX + directionY * directionY);
directionX /= len;
directionY /= len;
// Set the speed (move 100 pixels per second)
var speed = 100;
// Flag to check if we reached the target
var targetReached = false;
// Your update method with a delta time
// (time passed since last update in seconds)
function update(deltaTime){
// if we have reached the target, we can exit here
if(targetReached){
return;
}
// calculate remaining distance
var dx = targetX - player.x;
var dy = targetY - player.y;
var lenSquared = dx * dx + dy * dy;
// distance to cover in this update
var distToCover = deltaTime * speed;
// Check if the remaining distance is smaller than the
// distance to cover. If yes, set location to target location.
// Also set the "targetReached" flag to true
if(lenSquared < distToCover * distToCover){
player.x = targetX;
player.y = targetY;
targetReached = true;
} else {
player.x += distToCover * directionX;
player.y += distToCover * directionY;
}
};