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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…