javascript - 在每个确认的游戏中,Square 跌得更快
问题描述
我在画布上有正方形,当用户单击画布时它会上升。否则会掉下来。当正方形触地时,会出现游戏结束警报并期望用户采取行动。如果用户确认,游戏会重新开始,但这里的问题是,开始下降当用户想再次播放时总是更快。下面是我的 JS 代码。我怎样才能让它的下降速度与第一次一样恒定?
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
var recWidth,recHeight,xPos,yPos;
var gameStarted=false;
boxInitializer();
function startGame(){
this.gameStarted=true;
init();
}
function boxInitializer(){
this.recWidth = 100;
this.recHeight = 100;
this.xPos = (document.getElementById("gameCanvas").width/2) - (recWidth/2);
this.yPos = (document.getElementById("gameCanvas").height/2) - (recHeight/2);
ctx.fillRect(xPos,yPos,recWidth,recHeight);
console.log('XPos:'+xPos+'YPos:'+yPos);
}
function init(){
if(gameStarted){
const myVar=250;
this.c.addEventListener('click', Up,false);
setInterval(Down,myVar);
console.log(myVar);
setInterval(obstacleGenerator,2000);
function obstacleGenerator(){
console.log("Obstacle generated");
}
function drawSquare(){
this.ctx.fillRect(this.xPos,this.yPos,this.recWidth,this.recHeight);
}
function clearSquare(){
this.ctx.clearRect(this.xPos,this.yPos,this.recWidth,this.recHeight);
}
function Up()
{
clearSquare();
yPos-=40;
drawSquare();
}
function Down()
{
clearSquare();
this.yPos+=30;
console.log(yPos);
drawSquare();
if(this.yPos>=830){
this.gameStarted=false;
GameOver();
}
}
function GameOver(){
if (confirm("GAME OVER!")) {
clearSquare();
boxInitializer();
startGame();
} else {
}
}
}
}
解决方案
在这里你需要清除你的gameStarted
Down 间隔gameOver
你可以有一个变量来保持间隔,并在游戏结束功能中清除相同
var interval; // initialize at top
interval = setInterval(Down,myVar); // replace with this in `if(gameStarted)` loop
clearInterval(interval ) // clear interval on confirm("GAME OVER!")
推荐阅读
- c# - 无法重新编译检测代码
- jquery - 如果子元素不存在,则删除父元素
- haskell - 在列表上折叠部分应用的值构造函数?
- haskell - 如何禁用 <
> 使用 GHC 编译 Haskell 时出现异常? - java - 在没有 Web 服务器的 Spring-Boot 应用程序中,保持它运行的正确方法是什么?
- c# - ScreenPointToRay,该功能的背后是什么?
- python - pandas groupby 并用最小值更新
- angular - Angular 5 修复 Assets/ 文件夹的相对路径
- sql - 是否可以在不输入 sql 的情况下执行参数化存储过程
- python - 如何在硒中使用函数结尾?