I know this has been asked a few times before, but there has been no answer that actually works that I can find. There is a similar one, but the speed varies dependi
Live Demo
Below are the basics required to get what you need working,
var tx = targetX - x,
ty = targetY - y,
dist = Math.sqrt(tx*tx+ty*ty),
rad = Math.atan2(ty,tx),
angle = rad/Math.PI * 180;;
velX = (tx/dist)*thrust;
velY = (ty/dist)*thrust;
player.x += velX
player.y += velY
This is a demo I did a while back which sounds like what you are looking for, I added the ability to click in order to change the target based off of your issue.
window.addEventListener('mouseup', function(e) {
targetX = e.pageX;
targetY = e.pageY;
});
var ctx = document.getElementById("canvas").getContext("2d"),
x = 300,
y = 0,
targetX = Math.random()*300,
targetY = Math.random()*300,
velX = 0,
velY = 0,
thrust = 5;
function draw(){
var tx = targetX - x,
ty = targetY - y,
dist = Math.sqrt(tx*tx+ty*ty),
rad = Math.atan2(ty,tx),
angle = rad/Math.PI * 180;;
velX = (tx/dist)*thrust;
velY = (ty/dist)*thrust;
// stop the box if its too close so it doesn't just rotate and bounce
if(dist > 1){
x += velX;
y += velY;
}
ctx.fillStyle = "#fff";
ctx.clearRect(0,0,400,400);
ctx.beginPath();
ctx.rect(x, y, 10, 10);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "#ff0";
ctx.beginPath();
ctx.rect(targetX, targetY, 10, 10);
ctx.closePath();
ctx.fill();
setTimeout(function(){draw()}, 30);
}
draw();
Your problem seems to be that xRatio
and yRatio
are angles, not vector coordinates. This should work:
document.addEventListener('mouseup', function(e) {
movePlayer(selectedPlayer, {x:e.pageX, y:e.pageY});
});
function movePlayer(player, target) {
var start = {
x: player.x,
y: player.y,
t: Date.now()
},
distance = Math.sqrt(distance.x*distance.x + distance.y*distance.y),
time = distance; //This may seem pointless, but I will add a speed variable later
difference = {
x: target.x - player.x,
y: target.y - player.y,
t: time
};
player.angle = Math.atan2(distance.y, distance.x) * (180 / Math.PI);
//This function is called in another part of code that repeats it 60 times a second
walkPlayer = function(curTime) { // we need timing information here: Date.now()
var elapsed = curTime - start.t,
ratio = elapsed / difference.t;
player.x = start.x + difference.x * ratio;
player.y = start.y + difference.y * ratio;
if (ratio >= 1) {
player.x = target.x;
player.y = target.y;
// end calling of walkPlayer
}
};
}