人们。
今天我正在用画布写一个游戏,我遇到了一个问题。我已经做到了,当你点击画布时,玩家会移动到你点击的点。问题是,如果 x 大于 y,玩家将正确移动,直到到达 y 值的末尾,然后它转身前往 x 点。我需要它直接到我点击的地方。这是我的代码:
var canvas, ctx, fps;
canvas = $("#canvas")[0];
ctx = canvas.getContext("2d");
fps = 30;
window.onload = function(){init()}
function init(){
setInterval(function(){
draw();
}, 1000 / fps);
}
var backgroundTile = new Image();
backgroundTile.src = "img/background.png";
var lighting = new Image();
lighting.src = "img/lighting.png"
var sprite = new Image();
sprite.src = "img/sprite.png";
var spritePos = {
posX: 288,
posY: 208
}
var goX, goY;
goX = spritePos.posX;
goY = spritePos.posY;
function update(){
if (distance(spritePos.posX, spritePos.posY, goX, goY) <= 5){
spritePos.posX = goX;
}
if (distance(spritePos.posX, spritePos.posY, goX, goY) <= 5){
spritePos.posY = goY;
}
if(spritePos.posX > goX){
if(spritePos.posX - goX > 5){
spritePos.posX -= 5;
} else {
spritePos.posX = goX;
}
} else if(spritePos.posX < goX){
if(goX - spritePos.posX > 5){
spritePos.posX += 5;
} else {
spritePos.posX = goX;
}
}
if(spritePos.posY > goY){
if(spritePos.posY - goY > 5){
spritePos.posY -= 5;
} else {
spritePos.posY = goY;
}
} else if(spritePos.posY < goY){
if(goY - spritePos.posY > 5){
spritePos.posY += 5;
} else {
spritePos.posY = goY;
}
}
}
function drawSprite(){
ctx.drawImage(sprite, spritePos.posX, spritePos.posY);
}
function drawLighting(){
ctx.drawImage(lighting, (spritePos.posX - spritePos.posX) - 7, (spritePos.posY - spritePos.posY) - 7);
}
function drawBackground(){
ctx.drawImage(backgroundTile, 0, 0);
}
$("#canvas").click(function(e){
var x = e.pageX;
var y = e.pageY;
goX = x - 32;
goY = y - 32;
});
function draw(){
clean();
drawBackground();
update();
drawSprite();
drawLighting();
}
function clean(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function distance(pnt1X, pnt1Y, pnt2X, pnt2Y){
var xs = 0;
var ys = 0;
xs = pnt2X - pnt1X;
xs = xs * xs;
ys = pnt2Y - pnt1Y;
ys = ys * ys;
return Math.ceil(Math.sqrt(xs + ys));
}
我知道这个问题令人困惑,所以如果您需要更多信息,请告诉我。