Javascript 画布碰撞

Javascript 画布碰撞,javascript,canvas,2d-games,Javascript,Canvas,2d Games,我将画布碰撞编程到我的html游戏中。我已经检查了很多次,但是我没有发现代码有问题 // Handle left and right collisions with the canvas if (player.x <= canvas.x) { // Left edige player.xdir = 1; player.x = canvas.x; } else if (player.x + player.width >= canvas.x + canvas.wi

我将画布碰撞编程到我的html游戏中。我已经检查了很多次,但是我没有发现代码有问题

// Handle left and right collisions with the canvas
if (player.x <= canvas.x) {
    // Left edige
    player.xdir = 1;
    player.x = canvas.x;
} else if (player.x + player.width >= canvas.x + canvas.width) {
    // Right edge
    player.xdir = -1;
    player.x = canvas.x + canvas.width - player.width;
}

// Handle top and bottom collisions with the canvas
if (player.y <= canvas.y) {
    // Top edge
    player.ydir = 1;
    player.y = canvas.y;
} else if (player.y + player.height >= canvas.y + canvas.height) {
    // Bottom edge
    player.ydir = -1;
    player.y = canvas.y + canvas.height - player.height;
}
//处理画布的左右碰撞
if(player.x=canvas.x+canvas.width){
//右边缘
player.xdir=-1;
player.x=canvas.x+canvas.width-player.width;
}
//处理与画布的顶部和底部碰撞
if(player.y=canvas.y+canvas.height){
//底边
player.ydir=-1;
player.y=canvas.y+canvas.height-player.height;
}

我认为
canvas.x
这件事被误解了。画布中的所有内容相对于画布的原点始终是绝对的:

//用于“requestAnimationFrame”的Polyfill
window.requestAnimationFrame=window.requestAnimationFrame||
window.webkitRequestAnimationFrame||
window.mozRequestAnimationFrame||
window.msRequestAnimationFrame||
函数(回调){
设置超时(回调,1000/60);
};
//玩家对象
变量播放器={
x:50,
y:150,
xdir:1,
伊迪尔:1,
宽度:10,
身高:10
};
//画布(创建和附加)
var canvas=document.body.appendChild(document.createElement(“canvas”);
画布高度=200;
canvas.width=canvas.height;
//呈现上下文
var ctx=canvas.getContext(“2d”);
函数模拟(){
//移动播放器
如果(player.xdir==1){
player.x+=1;
}否则{
player.x-=1;
}
如果(player.ydir==1){
player.y+=1;
}否则{
player.y-=1;
}
//处理画布的左右碰撞
如果(player.x=canvas.width+player.width*0.5){
//右边缘
player.xdir=-1;
}
//处理与画布的顶部和底部碰撞
如果(player.y=canvas.height+player.height*0.5){
//底边
player.ydir=-1;
}
requestAnimationFrame(模拟);
//画出玩家(只是为了好玩)
ctx.fillStyle=“rgba(235235255,0.1)”;
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.fillStyle=“红色”;
ctx.fillRect(player.x-0.5*player.width,player.y-0.5*player.height,player.width,player.height);
}
//开始模拟
模拟()
画布{
背景色:rgba(235、235、255、0.1);

}
“我在代码中找不到问题”canvas.x是什么?我需要新鲜的眼睛@leu mSo我们使用玩家相对于画布的高度创建检测。@Teazzy1这是我的猜测。我不认为跟踪画布位置有什么意义,除非有一个名为canvas的变量跟踪视图端口位置。如果使用
requestAnimationFrame
而不是
setTimeout