提问人:CodeMaven42 提问时间:11/14/2023 更新时间:11/14/2023 访问量:40
地面未显示在 HTML5 画布游戏中 - JavaScript
Ground not displaying in HTML5 canvas game - JavaScript
问:
我正在使用 JavaScript 开发 HTML5 画布游戏,但我遇到了地面不显示的问题。我创建了一个 Ground 类来表示地面图块,并在 start 函数的循环中实例化它们。尽管如此,地面并没有在画布上呈现。
这是我代码的重要部分:
class Ground {
constructor(x, num, src) {
this.canvas = canvas;
this.context = this.canvas.getContext('2d');
this.ground = new Image();
this.ground.src = src;
this.width = this.ground.width;
this.height = this.ground.height;
this.position = {
x: (x + this.width) * num,
y: this.canvas.height - this.width,
};
}
create() {
let context = this.context;
context.drawImage(this.ground, this.position.x, this.position.y, this.width, this.height);
}
}
const canvas = document.querySelector('#canvas');
canvas.style.background = "#f9f9f9";
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ground = [];
for (let i = 0; i < 100; i++) {
let src = 'src/Tiles/Tile (2).png';
ground[i] = new Ground(0, i, src);
}
let start = () => {
requestAnimationFrame(start);
ground.forEach(ground => {
ground.create();
if (player.position.y + player.height <= ground.position.y && player.position.y + player.height + player.velocity.y >= ground.position.y && player.position.x + player.width >= ground.position.x && player.position.x <= ground.position.x + ground.width) {
player.velocity.y = 0;
doJump = true;
}
zombies.forEach(zombie => {
if (zombie.position.y + zombie.height <= ground.position.y && zombie.position.y + zombie.height + zombie.velocity.y >= ground.position.y && zombie.position.x + zombie.width >= ground.position.x && zombie.position.x <= ground.position.x + ground.width) {
zombie.velocity.y = 0;
}
});
});
}
start();
我已经检查了 Ground 类构造函数、地面的位置计算和渲染循环,但我无法确定问题所在。画布背景正在显示,其他游戏元素正在正确呈现。
有人可以帮我解决为什么地面不显示吗?
答: 暂无答案
评论
"load"
Ground