我试图在D键(右移)和A键(左移)时发生这些事件,但是当我在正确的位置输入正确的键码时,当我按下D键时它不起作用或S键移动。谁能告诉我有什么问题?我使用的是最新版本的Mozilla FireFox,但我不认为这是requestAnimFrame问题。
document.onkeydown = function(e)
{
e = e || window.event;
switch(e.which || e.keyCode)
{
case 37:
leftpress = true;
Context.clearRect( 0, 0, CanWidth, CanHeight ); // Clear the Canvas
Context.fillStyle = 'green';
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX + 5;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.fillText( "You move left.", 200, 100 );
leftanimate = true;
if ( jumppress == true )
{
leftjump = true;
}
break;
// case 38:
// jump();
// up/jump
//break;
case 39:
if ( rightpress == true )
{
rightanimate = true;
}
/*console.log("You move right");
Context.fillStyle = 'green';
OldBackgroundX = BackgroundX;
BackgroundX = BackgroundX - 20;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
Context.drawImage( ArrowRightImg, 400, 200 );// right
Context.fillText( "You move right.", 200, 100 );
break;
case 40: // down*/
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
};
document.onkeypress = function(event)
{
event = event || window.event;
switch(event.which || event.keyCode)
{
case 32:
jumppress = true;
if ( jumppress == true )
{
PJ = true;
}
if ( rightpress == true )
{
archjump = true;
}
if ( leftpress == true )
{
leftjump = true;
}
// up/jump
break;
/*
*
* Player Right Animation
*
*
* */
var Animation;
case 39:
rightpress = true;
if ( rightpress == true )
{
Context.clearRect( 0, 0, CanWidth, CanHeight ); // Clear the Canvas
//console.log("You move right");
Context.fillStyle = 'green';
BackgroundX = BackgroundX - 5;
Context.drawImage( FirstBackgroundImg, BackgroundX, BackgroundY, 1600, 800 );
rightanimate = true;
if ( jumppress == true )
{
archjump = true;
}
}
break;
}
}
document.onkeyup = function(event)
{
event = event || window.event;
switch(event.which || event.keyCode)
{
case 32:
jumppress = false;
break;
case 39:
rightpress = false;
break;
case 37:
leftpress = false;
}
}
答案 0 :(得分:2)
您使用错误的密钥代码绑定到WASD;您使用的代码对应于箭头键本身。
var KEY = {
WASD_LEFT: 65,
WASD_RIGHT: 68,
WASD_UP: 87,
WASD_DOWN: 83
}
document.onkeydown = function (e) {
switch (e.keyCode) {
case KEY.WASD_LEFT:
alert('Left');
break;
case KEY.WASD_RIGHT:
alert('Right');
break;
case KEY.WASD_UP:
alert('Up');
break;
case KEY.WASD_DOWN:
alert('Down');
break;
default:
return; // exit this handler for other keys
}
};