我有我的玩家对象和碰撞对象
var player = new Object();
player = {
x: window.innerWidth/2,
y: window.innerHeight/2,
width: 30,
height: 59,
aimAngle: 0,
speed: 5,
color: 'red',
};
var collision_object = new Object();
collision_object = {
x: 1080,
y: window.innerHeight/2+100,
width: 50,
height: 100,
color: 'yellow'
};
我定义了玩家和鼠标之间x,y坐标的距离
var mouseX;
var mouseY;
function handleMouseMovePlayer(e) {
mouseX = e.clientX - document.getElementById('canvas').getBoundingClientRect().left;
mouseY = e.clientY - document.getElementById('canvas').getBoundingClientRect().top;
mouseX -= player.x;
mouseY -= player.y;
mouseX = mouseX - player.width/2;
mouseY = mouseY - player.height/2;
}
$("#canvas").mousemove(function(e){handleMouseMovePlayer(e);});
我借助这个公式移动玩家
// search the angle
player.aimAngle = Math.atan2(mouseX,mouseY) / Math.PI * 180;
// function for making player move
function move_player() {
player.x+=Math.sin(player.aimAngle/180*Math.PI) * player.speed;
player.y+=Math.cos(player.aimAngle/180*Math.PI) * player.speed;
}
当onmouse down时,我将一个名为mouseDawn的变量提升为1,并且此函数创建move_player函数的间隔以使其移动,并清除鼠标未按下时的间隔,因此播放器停止
// on MOUSE DAWN EVENT
if (mouseDown==0) {
document.body.onmousedown = function() {
mouseDown++;
if (mouseDown==1) {
intervalID = setInterval(move_player,40);
}
};
}
我尝试了很多不同的碰撞类型,但没有任何帮助。例如,这个if语句检查玩家和碰撞对象之间的冲突是正确的,但是我不知道应该输入什么代码来使玩家停止(但不清楚间隔)
if (player.x < collision_object.x + collision_object.width &&
player.x + player.width > collision_object.x &&
player.y < collision_object.y + collision_object.height &&
player.y + player.height > collision_object.y) {
// I WAS TRYING THIS
player.speed = 1;
player.x-=1;
player.y-=1;
// this
player.x = collision_object.x - player.width;
}
但上面提到的所有变体仅适用于一侧x或y。如果我为两边制作代码(从左到右,从右到左进入游戏到碰撞对象)代码只需+1 -1逻辑,并且不做任何看法。