【发布时间】:2018-01-20 21:08:39
【问题描述】:
我正在尝试使用 html5 画布创建一个非常基本的 javascript 游戏。因此,我创建了一个主播放器“类”,它应该在实例化和调用“init 方法”时在画布上创建一个红色圆圈。最后,它也应该可以通过箭头键进行控制,为此,我尝试将事件侦听器添加到文档中,检查 keydown/keyup 是否会更改布尔值,例如 leftPressed = true;等基于此,displace 方法(在 setInterval 函数 draw 中调用)旨在更新红色圆圈的位置,这就是我的问题所在 - 打开 index.html 文件时,会创建红色圆圈,但是当我按箭头键,我不能让它移动。任何帮助将不胜感激,请原谅我的无知,我大约一周前开始使用 javascript。
这是包含播放器“类”的js代码:
canvas = document.getElementById("surface");
ctx = canvas.getContext("2d");
//user controlled player class
player = function(x,y,dx,dy,radius) {
this.x = x;
this.y = y;
this.speedx = dx;
this.speedy = dy;
this.radius = radius;
this.leftPressed = false;
this.rightPressed = false;
this.upPressed = false;
this.downPressed = false;
document.addEventListener("keydown",this.onKeyDown,false);
document.addEventListener("keyup",this.onKeyUp,false);
this.init = function() {
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,Math.PI*2);
ctx.fillStyle = "red";
ctx.fill();
ctx.closePath();
}
this.onKeyDown = function(e) {
if (e.keyCode == 37) {
this.leftPressed = true;
}
if (e.keyCode == 38) {
this.upPressed = true;
}
if (e.keyCode == 39) {
this.rightPressed = true;
}
if (e.keyCode == 40) {
this.downPressed = true;
}
}
this.onKeyUp = function(e) {
if (e.keyCode == 37) {
this.leftPressed = false;
}
if (e.keyCode == 38) {
this.upPressed = false;
}
if (e.keyCode == 39) {
this.rightPressed = false;
}
if (e.keyCode == 40) {
this.downPressed = false;
}
}
this.displace = function() {
if (this.leftPressed) {
this.x -= this.speedx;
}
if (this.rightPressed) {
this.x += this.speedx;
}
if (this.downPressed) {
this.y -= this.speedy;
}
if (this.upPressed) {
this.y += this.speedy;
}
}
}
这是 main.js 代码:
canvas = document.getElementById("surface");
ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.width,canvas.height);
player1 = new player(500,500,7,7,25);
function draw() {
ctx.fillStyle = "black";
ctx.fillRect(0,0,canvas.width,canvas.height);
player1.init();
player1.displace();
}
setInterval(draw,10);
【问题讨论】:
标签: javascript html canvas html5-canvas