如果我的玩家走在瓷砖上(water1,water2,water3变量),我正试图重置一个条形图。当玩家与这三个图块中的一个发生碰撞时,条形图会重置。如果我的播放器没有在瓷砖上行走并且条形图为100,则会显示游戏结束屏幕。
它到目前为止工作,但问题是,当玩家与水砖碰撞时,栏重置开始,但游戏结束屏幕的计数器没有重置。
例如:如果我在40%时重置条形,它会回到0,但是在条形图再次变为60%之后,我得到游戏结束屏幕,而不是100%像我想要的那样。
var water1 = {x: 352, y: 64, width: 32, height: 32}
var water2 = {x: 352, y: 96, width: 32, height: 32}
var water3 = {x: 384, y: 64, width: 32, height: 32}
function thirst() {
var elem2 = document.getElementById("durst");
var width = 1;
var id2 = setInterval(frame, 1000);
function frame() {
if (player.xPos < water1.x + water1.width &&
player.xPos + player.width > water1.x &&
player.yPos < water1.y + water1.height &&
player.height + player.yPos > water1.y) {
thirst();
return;
} if (player.xPos < water2.x + water2.width &&
player.xPos + player.width > water2.x &&
player.yPos < water2.y + water2.height &&
player.height + player.yPos > water2.y) {
thirst();
return;
} if (player.xPos < water3.x + water3.width &&
player.xPos + player.width > water3.x &&
player.yPos < water3.y + water3.height &&
player.height + player.yPos > water3.y) {
thirst();
return;
} if (width >= 100) {
clearInterval(id2);
} else {
width++;
elem2.style.width = width + '%';
} if(width == 100) {
location.href = '666_GameOver.html';
}
}
}
CSS
#balkenDurst {
width: 5%;
background-color: #0000ff;
z-index: 4;
position: absolute;
margin-left: 8% ;
}
#durst {
width: 0%;
height: 30px;
background-color: #ffffff;
z-index: 4;
}
HTML
<div id="balkenDurst">
<div id="durst"></div>
</div>
也许你知道什么是错的。
我知道我可以用更少的代码编写它,但我正在学习,我很高兴到目前为止它的工作原理。
好的,我通过碰撞检测和您使用的方法看到您接近目标。 代码存在一些问题,您可以自行修复。 但我得到了一些指示。
在你的代码中:
if (player.xPos < water1.x + water1.width &&
player.xPos + player.width > water1.x &&
player.yPos < water1.y + water1.height &&
player.height + player.yPos > water1.y) {
thirst();
return;
}
这重复多次。尽量避免反复重复相同的代码。 您可以轻松地将其更改为可以多次调用的功能。
这是一个例子:
function hit( tile) {
//Hits on x axis
if(player.xPos < tile.x + tile.width && player.xPos + player.width > tile.x) {
//Hits on y axis
if (player.yPos < tile.y + tile.height && player.yPos + player.height > tile.y) {
return true;
}
}
return false;
}
注意:现在阅读代码不容易吗?现在,因为我们已经成为一个功能,它可以采取任何瓷砖!
就像说水瓦。
//Defines our water tiles in an array. (Easier to use)
var waterTiles = [
{x: 352, y: 64, width: 32, height: 32},
{x: 352, y: 96, width: 32, height: 32},
{x: 384, y: 64, width: 32, height: 32},
];
//Checks if any of the water tiles hit
function checkHits() {
for (var i = 0; i < waterTiles.length; i++) {
//Use our method above.
var check = hit ( waterTiles[i] );
if (check) {
//Code to check if it hits.
}
}
}
这很好,但你没有回答我的问题。 好的,那就是你游戏的干渴逻辑。
上面的代码中没有显示您如何使用口渴栏进行设置。
但由于你的解渴栏没有重置,可能听起来像是一个没有正确重置的变量。
如果你有一个var thirst
定义和一个var width
的酒吧。你需要改变它们。
所以在你的口渴方法中设定口渴水平:player.thirst = 60;
(例子)。
然后在你的frame()方法(通常在游戏循环中称为“更新”)得到这样的东西:var width = player.thirst
减少它(每帧?)只需再次设置变量:player.thirst = player.thirst - 1;