我正在关注youtube教程并且他的示例工作正常,应该有一个红色框我可以使用w,a,s和d键移动。我不确定在这个例子中我错过了什么。我相信错误发生在main.js文件中,因为对该文件进行了大多数更改。
//Errors
keys.js:15 Uncaught SyntaxError: missing ) after argument list
main.js:16 Uncaught ReferenceError: key is not defined at update (main.js:16) at main (main.js:29)
// main.js
var canvas = document.getElementById("screen");
var context = canvas.getContext("2d");
var x = 20, y = 20;
function init() {
context.fillStyle = "red";
}
function move(dx, dy) {
x += dx;
y += dy;
}
function update() {
if(key.a) {move(-5, 0);}
if(key.d) {move( 5, 0);} // moves sprite 5 in x direction and 0 in y direction
if(key.w) {move( 0, -5);}
if(key.s) {move( 0, 5);}
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height); // clear every pixel from top left to bottom right
context.fillRect(x, y, 50, 50); //how far from left, top, 50x50
}
function main() {
update();
draw();
}
window.onload = function() {
init();
setInterval(main, 1000 / 60); //call main once every 1000/60 milliseconds
};
这是应该处理键绑定的js
// keys.js
var key = {
a: false,
d: false,
s: false,
w: false
};
window.addEventListener('keydown', function(event) {
switch(event.which || event.keyCode) {
case 65: key.a = true; break; // 37 <- left
case 68: key.d = true; break; // 39 <- right
case 83: key.s = true; break; // 40 <- down
case 87: key.w = true; break; // 38 <- up
}
}};
window.addEventListener('keyup', function(event) {
switch(event.which || event.keyCode) {
case 65: key.a = false; break; // 37 <- left
case 68: key.d = false; break; // 39 <- right
case 83: key.s = false; break; // 40 <- down
case 87: key.w = false; break; // 38 <- up
}
}};
答案 0 :(得分:1)
如果key
未定义,则可能是因为它们位于单独的文件中并且不按顺序包含。尝试在keys.js
之前将main.js
包含在托管这两者的任何文件中。
至于此错误:keys.js:15 Uncaught SyntaxError: missing ) after argument list
问题在于您的addEventListener
函数调用。它们都应在}};
时以});
结尾。见下文:
window.addEventListener('keydown', function(event) {
switch(event.which || event.keyCode) {
case 65: key.a = true; break; // 37 <- left
case 68: key.d = true; break; // 39 <- right
case 83: key.s = true; break; // 40 <- down
case 87: key.w = true; break; // 38 <- up
}
}); // <-- Corrected
window.addEventListener('keyup', function(event) {
switch(event.which || event.keyCode) {
case 65: key.a = false; break; // 37 <- left
case 68: key.d = false; break; // 39 <- right
case 83: key.s = false; break; // 40 <- down
case 87: key.w = false; break; // 38 <- up
}
}); // <-- Corrected