【发布时间】:2019-05-23 01:42:57
【问题描述】:
问题是,HTML 画布没有在画布内输出字符对象。画布定义为gameArea,字符定义为字符。两者都是用 JavaScript 编写的,并且字符被制作成一个对象。
这是一款 2D 平台游戏,到目前为止,我已经尝试将角色从对象更改为变量,以查看对象的封装是否导致问题,但这没有奏效。我还尝试在角色对象中添加一个名为 update 的新函数,以确保角色(矩形)在移动时被填充。
这是我的代码:
第一部分声明了字符变量,还有一个函数,在HTML中首先使用onload启动:
var Character;
function startGame(){
gameArea.start();
Character = new character(40, 80, "#4286f4", 30, 500, true, 0, 0);
}
角色对象的参数有width、height、colour、x、y、跳跃状态、speedX和speedY(后面的代码也会显示)。
第二部分显示了gameArea变量(画布),我在这里也调用了我的Keydown和Keyup的EventListeners:
var gameArea = {
canvas: document.getElementById("canvas"), //Defining the canvas'
//dimensions
start: function() {
this.canvas.width = 700;
this.canvas.height = 500;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas,document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {//EventListener
functions
gameArea.keys = (gameArea.keys || []);
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
window.addEventListener('keyup', function (e) {
gameArea.keys[e.keyCode] = (e.type == "keydown");
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
下一节是字符对象:
function character(width, height, color, x, y, jumping, speedX, speedY)
{//Character object, blue rectangle
this.jumping=jumping;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = speedX;
this.speedY= speedY;
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.width, this.height, this.x, this.y);
this.update = function() {//Updating the gameArea function
ctx = gameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
据我所知,上面的代码是唯一与该问题相关的代码。如果需要,可以在下面找到其余代码(控制器逻辑和运动机制):
function updateGameArea() {
gameArea.clear();
character.speedX = 0;
character.speedY = 0;
character.update();
var controller = {
up: false,
down: false,
left: false,
right: false,
keyListener: function (event) {
var keyPosition = (event.type == "keydown") ? true : false;
switch (event.keyCode) {
case 87:
controller.up = keyPosition;
break;
case 83:
controller.down = keyPosition;
break;
case 65:
controller.left = keyPosition;
break;
case 68:
controller.right = keyPosition;
break;
}
}
};
if (controller.up && character.jumping == false) {
character.speedY -= 2.5
character.jumping = true;
}
if (controller.down) {
character.speedY += 2.5;
}
if (controller.left) {
character.speedX -= 2.5;
}
if (controller.right) {
character.speedX += 2.5;
}
character.speedY += 1.5;
character.x = character.speedX;
character.y = character.speedY;
character.speedX *= 0.9;
character.speedY *= 0.9
var ground = gameArea.canvas.height - this.height;
if (this.y > ground) {
character.jumping = false;
character.y = ground;
character.speedY = 0;
}
}
预期结果:角色显示在画布内并且动作正确
实际结果:字符不显示。
我知道这里有很多代码,但如果有人能指出我正确的方向,我将不胜感激,因为我真的不明白为什么角色没有显示在画布中。
非常感谢!
【问题讨论】:
标签: javascript html oop canvas