球不顺畅

时间:2013-06-27 20:56:35

标签: javascript canvas keypress

我想用箭头做一个简单的移动球,所以我做了:

<canvas id="canvas" width="300" height="300" ></canvas>

<script>
var x=120;
var y=120;
var key,pos=0;

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function()
{
    ctx.drawImage(img,x,y);
}
img.src="http://www.infogridpacific.com/blog/i/ball_online.png";

document.onkeydown=function(e)
{
    pos=1;
    key=window.event?e.keyCode:e.which;
}
document.onkeyup=function(e){pos=0;}

setInterval(function()
{
    if(pos==0)return;
    if(key==37)x-=2;
    if(key==38)y-=2;
    if(key==39)x+=2;
    if(key==40)y+=2;
    canvas.width=canvas.width;
    ctx.drawImage(img,x,y);
},5);
</script>

http://jsfiddle.net/mageek/ny3uz/6/

但是如果你向右做,那么球停止一秒然后开始向相反的方向移动。知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

我怀疑你按下右箭头键时可能仍然按住左箭头键,然后稍微放开左箭头。

所以事件的顺序如下:

(you press left)             key=37 pos=1
(ball moves left for a bit)
(you press right)            key=39 pos=1
(you let go of left)         key=39 pos=0
(the ball stops moving)
(1s later the OS autorepeat kicks in) key=39 pos=1
(ball moves right)

您需要跟踪已按下/释放的键数,和/或在up事件中使用键代码来检查引发了哪个键。理想情况下,不要只记录最后一个按键的值,而是跟踪当前所有按键的值。

此版本非常流畅,也可让您沿对角线移动:

var x=120;
var y=120;
var key = [];

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function()
{
    ctx.drawImage(img,x,y);
}
img.src="http://www.infogridpacific.com/blog/i/ball_online.png";

document.onkeydown=function(e)
{
    code=window.event?e.keyCode:e.which;
    key[code]=1;
}
document.onkeyup=function(e)
{
    code=window.event?e.keyCode:e.which;
    key[code]=0;
}

setInterval(function()
{
    if(key[37])x-=2;
    if(key[38])y-=2;
    if(key[39])x+=2;
    if(key[40])y+=2;
    canvas.width=canvas.width;
    ctx.drawImage(img,x,y);
},5);

答案 1 :(得分:1)

简单地计算按键/释放次数。这样,如果按下两个键,它就不会停止。

var x=120;
var y=120;
var key,pos=0;

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function(){
ctx.drawImage(img,x,y);
}
img.src="http://www.infogridpacific.com/blog/i/ball_online.png";

document.onkeydown=function(e){
pos++;
key=window.event?e.keyCode:e.which;
}
document.onkeyup=function(e){pos--}

setInterval(function(){
if(pos==0)return;
if(key==37)x-=2;
if(key==38)y-=2;
if(key==39)x+=2;
if(key==40)y+=2;
canvas.width=canvas.width;
ctx.drawImage(img,x,y);
},5);

http://jsfiddle.net/stMh9/