我今天创建了一个 2d 平台游戏。玩家可以左右移动和跳跃。不允许爬上墙的一侧。当您在墙壁旁边按例如向右和向上时,它会爬上墙壁。你能看看,说我错过了什么。
function updateMe()
{
x+=vx;
y+=vy;
//gravity
vy+= gravity;
if(y>=HEIGHT-playerH)
{
y=HEIGHT-playerH;
vy=0;
}
//collision y
var maxR=WIDTH/tileW-1;
if(vy>0)
{
//going down
var temp2 = Math.floor((y+vy+playerH)/tileH);
for(var i=Math.max(0,Math.floor(x/tileW)),len=Math.min(maxR,Math.ceil((x+playerW)/tileW)); i<len; i++)
{
if(map[temp2][i]!=0)
{
y=temp2*tileH-playerH;
vy=0;
break;
}
}
}
else if(vy<0)
{
//going down
var temp2 = Math.floor((y+vy)/tileH);
for(var i=Math.max(0,Math.floor(x/tileW)),len=Math.min(maxR,Math.ceil((x+playerW)/tileW)); i<len; i++)
{
if(map[temp2][i]!=0)
{
y=temp2*tileH+tileH;
vy=0.01;//make it fall down
break;
}
}
}
//momentum
if(vx>0)
vx-=momentum/2;
else if(vx<0)
vx+=momentum/2;
//collsion
maxR=WIDTH-playerW;
if(vx>0)
{
//going right
if(x+vx<maxR)
{
var temp2 = Math.floor((x+vx+playerW)/tileW);
for(var i=Math.floor(y/tileH),len=Math.ceil((y+playerH)/tileH); i<len; i++)
{
if(map[i][temp2]!=0)
{
x=temp2*tileW-playerW;
vx=0;
break;
}
}
}
else
{
vx=maxR-x;
}
}
else if(vx<0)
{
//going left
if(x+vx>0)
{
var temp2 = Math.floor((x+vx)/tileW);
for(var i=Math.floor(y/tileH),len=Math.ceil((y+playerH)/tileH); i<len; i++)
{
if(map[i][temp2]!=0)
{
x=temp2*tileW+tileW;
vx=0;
break;
}
}
}
else
{
vx=x;
}
}
//x boundaries
if(x<=0)
{
x=vx=0;
}
else if(x>=WIDTH-playerW)
{
x=WIDTH-playerW;
}
//draw
ctx.fillRect(x,y,playerW,playerH);
}