2013-02-07 30 views
0

我使用KineticJS的transitionTo在箭头键(keydown事件)的帮助下制作了一个形状。

我有2个问题:

1.按压形状的移动具有短延迟密钥后。我如何消除延迟? ?

2.如何让形状同时按下两个箭头键角移动这里是JavaScript:Keydown的KineticJS形状运动

var stage = new Kinetic.Stage({ 
    container: 'container', 
    width: screen.width, 
    height: 500 
}); 
var layer = new Kinetic.Layer(); 

var circle = new Kinetic.Circle({ 
    x: stage.getWidth()/2, 
    y: stage.getHeight()/2, 
    radius: 70, 
    fill: 'yellow', 
    stroke: 'black', 
    strokeWidth: 4 
}); 

// add the shape to the layer 
layer.add(circle); 

// add the layer to the stage 
stage.add(layer); 

window.addEventListener('keydown', function(e) { 
    if (e.keyCode == 37) { //Left Arrow Key 
     setTimeout(function() { 
      circle.transitionTo({ 
       x: circle.getX() - 10, 
       y: circle.getY(), 
       duration: 0.01 
      }) 
     }, 0); 
    } 
    if (e.keyCode == 38) { //Up Arrow Key 
     setTimeout(function() { 
      circle.transitionTo({ 
       x: circle.getX(), 
       y: circle.getY() - 10, 
       duration: 0.01 
      }) 
     }, 0); 
    } 
    if (e.keyCode == 39) { //Right Arrow Key 
     setTimeout(function() { 
      circle.transitionTo({ 
       x: circle.getX() + 10, 
       y: circle.getY(), 
       duration: 0.01 
      }) 
     }, 0); 
    } 
    if (e.keyCode == 40) { //Top Arrow Key 
     setTimeout(function() { 
      circle.transitionTo({ 
       x: circle.getX(), 
       y: circle.getY() + 10, 
       duration: 0.01 
      }) 
     }, 0); 
    } 
}); 

小提琴:http://jsfiddle.net/uUWmC/1/

+1

1.看不到任何延迟,感觉响应我。 2.请参阅[这里](http://stackoverflow.com/questions/7614340/listen-to-multiple-keydowns)(玩'超时值')。为什么你在'setTimeout'中包含'transitionTo'? –

回答

1

对于延迟,您可以解开setTimeout和transitionTo如下所示;

window.addEventListener('keydown', function(e) { 
    if (e.keyCode == 37) //Left Arrow Key 
     circle.attrs.x -= 10; 
    if (e.keyCode == 38) //Up Arrow Key 
     circle.attrs.y += 10; 
    if (e.keyCode == 39) //Right Arrow Key 
     circle.attrs.x += 10; 
    if (e.keyCode == 40) //Top Arrow Key 
     circle.attrs.y -= 10; 
    layer.draw(); 
}); 

对于对角线移动,您不能同时按两个箭头键。这是您的操作系统限制。你可以按alt键,ctrl键......等。

0

检测对角线移动以跟踪哪些按键已被按下/释放的最佳方式。我使用所谓的“key_status.js”一个jQuery插件,它允许你检查的东西,如任意键的状态:

if (keydown.left) { 
    console.log("left arrow is down") 
} 
if (keydown.left && keydown.up) { 
    console.log("Left/Up Diagonal!") 
} 

当然,要做到这样的事情,你需要换一个setTimeout的所有输入检查或requestAnimFrame。 http://www.html5rocks.com/en/tutorials/canvas/notearsgame/

直接链接脚本:

我在优秀的HTML5游戏的教程在这里发现了这个脚本和方法(http://strd6.com/space_demo/javascripts/key_status.js