因此,我目前正在作为学校课程的编程项目来开发一款游戏,我遇到了一个问题,即玩家似乎无法通过“触摸”顶部和底部的墙壁而死亡,左右墙壁虽然起作用。这是墙壁的代码:
class Wall{
constructor(x, y, w, h, c){
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.color = c;
}
draw(ctx){
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
var Wall1 = new Wall(0,0, 3, 850, "cyan");
var Wall2 = new Wall(600, 0, 3, 850, "cyan");
var Wall3 = new Wall(0, 425, 600, 3, "cyan");
function collision(ctx){
//Spelare 1
if(NotP1.x < Wall1.x + Wall1.width && NotP1.x > Wall1.x){
NotP1.x = NotP2.x;
return alert("Player 1 died, Player 2 Wins");
}
else if(NotP1.x > Wall2.x + Wall2.width && NotP1.x > Wall2.x){
NotP1.x = NotP2.x;
return alert("Player 1 died, Player 2 Wins");
}
else if(NotP1.x > Wall3.y + Wall3.height && NotP1.x > Wall3.y){
NotP1.x = NotP2.x;
return alert("Player 299 died, Player 2 Wins");
}
//Spelare 2
if(NotP2.x < Wall1.x + Wall1.width && NotP2.x > Wall1.x){
NotP2.x = NotP1.x;
return alert("Player 2 died, Player 1 Wins");
}
else if(NotP2.x > Wall2.x + Wall2.width && NotP2.x > Wall2.x){
NotP2.x = NotP1.x;
return alert("Player 2 died, Player 1 Wins");
}
Wall3.draw(ctx);
}
您正在比较玩家的X值和墙壁的Y值
else if(NotP1.x > Wall3.y + Wall3.height && NotP1.x > Wall3.y){
我在碰撞函数中更改了一些代码
function collision(ctx){
if(NotP1.x <= Wall1.x || NotP1.x >= Wall2.x ||
NotP1.y <= Wall3.y + Wall3.height &&
NotP1.y >= Wall3.y || NotP1.y >= 850) {
NotP1.x = spawn1;
alert("Player 1 died, Player 2 Wins");
}
if(NotP2.x <= Wall1.x || NotP2.x >= Wall2.x ||
NotP2.y <= Wall3.y + Wall3.height &&
NotP2.y >= Wall3.y || NotP2.y <= 0) {
NotP2.x = NotP1.x;
alert("Player 2 died, Player 1 Wins");
}
Wall3.draw(ctx);
}