键盘响应
优质
小牛编辑
137浏览
2023-12-01
键盘移动
只需再做一点微小的工作,你就可以建立一个通过鼠标控制精灵移动的简单系统。为了简化你的代码,我建议你用一个名为keyboard
的自定义函数来监听和捕捉键盘事件。
function keyboard(keyCode) {
let key = {};
key.code = keyCode;
key.isDown = false;
key.isUp = true;
key.press = undefined;
key.release = undefined;
//The `downHandler`
key.downHandler = event => {
if (event.keyCode === key.code) {
if (key.isUp && key.press) key.press();
key.isDown = true;
key.isUp = false;
}
event.preventDefault();
};
//The `upHandler`
key.upHandler = event => {
if (event.keyCode === key.code) {
if (key.isDown && key.release) key.release();
key.isDown = false;
key.isUp = true;
}
event.preventDefault();
};
//Attach event listeners
window.addEventListener(
"keydown", key.downHandler.bind(key), false
);
window.addEventListener(
"keyup", key.upHandler.bind(key), false
);
return key;
}
keyboard
函数用起来很容易,可以像这样创建一个新的键盘对象:
let keyObject = keyboard(asciiKeyCodeNumber);
这个函数只接受一个参数就是键盘对应的ASCII键值数,也就是你想监听的键盘按键。 这是键盘键ASSII值列表).
然后给键盘对象赋值press
和release
方法:
keyObject.press = () => {
//key object pressed
};
keyObject.release = () => {
//key object released
};
键盘对象也有 isDown
和 isUp
的布尔值属性,你可以用它们来检查每个按键的状态。
在examples
文件夹里看一下keyboardMovement.html
文件是怎么用keyboard
函数的,利用键盘的方向键去控制精灵图。运行它,然后用上下左右按键去让猫在舞台上移动。
这里是代码:
//Define any variables that are used in more than one function
let cat, state;
function setup() {
//Create the `cat` sprite
cat = new Sprite(resources["images/cat.png"].texture);
cat.y = 96;
cat.vx = 0;
cat.vy = 0;
app.stage.addChild(cat);
//Capture the keyboard arrow keys
let left = keyboard(37),
up = keyboard(38),
right = keyboard(39),
down = keyboard(40);
//Left arrow key `press` method
left.press = () => {
//Change the cat's velocity when the key is pressed
cat.vx = -5;
cat.vy = 0;
};
//Left arrow key `release` method
left.release = () => {
//If the left arrow has been released, and the right arrow isn't down,
//and the cat isn't moving vertically:
//Stop the cat
if (!right.isDown && cat.vy === 0) {
cat.vx = 0;
}
};
//Up
up.press = () => {
cat.vy = -5;
cat.vx = 0;
};
up.release = () => {
if (!down.isDown && cat.vx === 0) {
cat.vy = 0;
}
};
//Right
right.press = () => {
cat.vx = 5;
cat.vy = 0;
};
right.release = () => {
if (!left.isDown && cat.vy === 0) {
cat.vx = 0;
}
};
//Down
down.press = () => {
cat.vy = 5;
cat.vx = 0;
};
down.release = () => {
if (!up.isDown && cat.vx === 0) {
cat.vy = 0;
}
};
//Set the game state
state = play;
//Start the game loop
app.ticker.add(delta => gameLoop(delta));
}
function gameLoop(delta){
//Update the current game state:
state(delta);
}
function play(delta) {
//Use the cat's velocity to make it move
cat.x += cat.vx;
cat.y += cat.vy
}