用按键移动元素(多个) [英] move element with keypress (multiple)
问题描述
对角移动不起作用,并且同时在long-longPress/right上发出
Diagonal move not working and issue on left-longPress/right simultaneous
但是在两次按键下,船发疯了!
But on double keypress the ship goes crazy!
$(document).bind('keydown', function(e) {
var box = $("#plane"),
left = 37,
up = 38,
right = 39,
down = 40
if (e.keyCode == left) {
box.animate({left: "-=5000"},3000);
}
if (e.keyCode == up) {
box.animate({top: "-=5000"},3000);
}
if (e.keyCode == right) {
box.animate({left:"+=5000"},3000);
}
if (e.keyCode == down) {
box.animate({top: "+=5000"},3000);
}
});
$(document).bind('keyup', function() {
$('#plane').stop();
});
推荐答案
依靠键盘事件移动元素将使其依赖于OS键间隔延迟. 相反,请使用游戏间隔并检查存储在对象中的按下键
Relying on keyboard events to move an element will make it dependent on the OS key-interval delay. Instead, use the game interval and check the pressed keys stored inside an Object
在keydown keyup
事件上,如果event.which
返回的keyCode为>=37 && <=40
,则表示使用了箭头键.在K
(键)对象内存储键号属性的布尔值.
On keydown keyup
events, if the keyCode returned by event.which
is >=37 && <=40
means arrow keys were used. Store inside a K
(keys) Object a boolean value for key-number property.
如果键编号属性(在我们的K
对象内部)为true
(if(K[37])
),则在window.requestAnimationFrame
内部增加或减少元素的x
,y
位置.
Inside a window.requestAnimationFrame
increase or decrease the x
, y
position of your element if a key-number property (inside our K
object) is true
(if(K[37])
).
同时使用对角线移动元素,即↑ 和→ 需要对角线距离的补偿:1 / Math.sqrt(2)
(0.7071 ..)
Moving an element diagonally using simultaneously i.e. the ↑ and → needs a compensation for the diagonal distance: 1 / Math.sqrt(2)
(0.7071..)
const Player = {
el: document.getElementById('player'),
x: 200,
y: 100,
speed: 2,
move() {
this.el.style.transform = `translate(${this.x}px, ${this.y}px)`;
}
};
const K = {
fn(ev) {
const k = ev.which;
if (k >= 37 && k <= 40) {
ev.preventDefault();
K[k] = ev.type === "keydown"; // If is arrow
}
}
};
const update = () => {
let dist = K[38] && (K[37] || K[39]) || K[40] && (K[37] || K[39]) ? 0.707 : 1;
dist *= Player.speed;
if (K[37]) Player.x -= dist;
if (K[38]) Player.y -= dist;
if (K[39]) Player.x += dist;
if (K[40]) Player.y += dist;
Player.move();
}
document.addEventListener('keydown', K.fn);
document.addEventListener('keyup', K.fn);
(function engine() {
update();
window.requestAnimationFrame(engine);
}());
#player{
position: absolute;
left: 0; top: 0;
width: 20px; height: 20px;
background: #000; border-radius: 50%;
}
Click here to focus, and use arrows
<div id="player"></div>
这篇关于用按键移动元素(多个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!