我正在尝试制作一个类似于帆布的“ roguelike”游戏,但遇到了一些麻烦。
我想做什么:
我想在我的游戏循环中实现“转弯”系统,以便仅在发生转弯事件时才运行。
这里有一些代码,您可以看到我在说什么:
我的index.js
let canvas = document.getElementById('gameScreen');
let ctx = canvas.getContext('2d');
const GAME_WIDTH = 1024;
const GAME_HEIGHT = 1024;
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
let lastTime = 0;
let game = new Game(GAME_WIDTH, GAME_HEIGHT);
game.start();
function gameLoop() {
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
game.draw(ctx);
requestAnimationFrame(gameLoop);
}
requestAnimationFrame(gameLoop);
我的game.js:
import Player from './player.js';
import InputHandler from './input.js';
import { buildLevel, map1 } from './levels.js';
export default class Game {
constructor(gameWidth, gameHeight) {
this.gameWidth = gameWidth;
this.gameHeight = gameHeight;
this.player = new Player(this);
this.gameObjects = [];
this.walls = [];
this.levels = [map1];
this.currentLevel = 0;
new InputHandler(this.player, this);
}
start() {
this.walls = buildLevel(this, this.levels[this.currentLevel]);
console.log('yes');
this.gameObjects = [this.player];
}
update(deltaTime) {
console.log('update');
}
draw(ctx) {
console.log('draw');
[...this.gameObjects, ...this.walls].forEach(object => object.draw(ctx));
}
}
因此,现在我可以开始游戏,生成地图,有了玩家,就可以移动他。让我感到困扰的是,“ draw()”函数一直在循环运行。
仅在触发转弯事件时重新绘制游戏或玩家的正确方法是什么?
希望我没有让您感到困惑,谢谢!
您可以使用与此类似的内容。您可以在turn事件中更改isTurn
布尔值的状态,并在gameLoop中使用if
来检查其值,并且如果为True,则仅运行draw()
方法。
var isTurn = false;
function gameLoop() {
if(isTurn){
ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
game.draw(ctx);
requestAnimationFrame(gameLoop);
}
}