输入
Pyxen 支持键盘、触控、鼠标和手柄输入。所有输入通过 input 模块读取,在 update() 运行之前每帧更新一次。
键盘
通过 input.keyboard 上的名称访问任何按键:
if input.keyboard.right.down:
player.x += 2
if input.keyboard.space.pressed:
jump()
每个按键暴露相同的属性:
| 属性 | 含义 |
|---|---|
down | 此帧被按住 |
pressed | 此帧刚按下(仅一帧为 true) |
released | 此帧刚释放(仅一帧为 true) |
value | 模拟值(按键为 0.0 或 1.0) |
常见按键名称:left、right、up、down、space、enter、escape、a–z、0–9。
触控
在 iPad 上,触控输入通过 input.touches 获取——活跃触点的列表:
for touch in input.touches:
if touch.started:
spawn_particle(touch.x, touch.y)
每个触点具有:
| 属性 | 含义 |
|---|---|
x, y | 游戏坐标中的位置 |
dx, dy | 自上一帧以来的移动 |
pressure | 触控压力(如果可用) |
down | 当前正在触控 |
started | 此帧开始触控 |
ended | 此帧结束触控 |
鼠标
鼠标输入在 Mac 和连接了鼠标或触控板的 iPad 上工作:
if input.mouse.buttons.left.pressed:
shoot(input.mouse.x, input.mouse.y)
鼠标暴露:
x,y— 游戏坐标中的光标位置dx,dy— 自上一帧以来的移动wheel— 滚轮增量buttons.left、buttons.right、buttons.middle— 各自具有down、pressed、released
手柄
Pyxen 支持最多 4 个手柄。通过 input.gamepads 访问:
pad = input.gamepads[0]
if pad.connected:
player.x += pad.left_stick.x * 2
if pad.buttons.a.pressed:
jump()
每个手柄具有:
connected— 此索引是否有手柄连接left_stick、right_stick— 模拟摇杆,具有x和y(-1.0 到 1.0)buttons—a、b、x、y,加上扳机键和肩键,各自具有down、pressed、released、value
为多种输入设计
Pyxen 游戏可以在 iPad 上使用触控运行,在 iPad 上使用键盘运行,或在 Mac 上使用鼠标和键盘运行。一个好的方法是检查多种输入源:
def update():
dx = 0
if input.keyboard.right.down:
dx = 2
elif input.keyboard.left.down:
dx = -2
pad = input.gamepads[0]
if pad.connected:
dx = pad.left_stick.x * 2
player.x += dx
完整 API 参见输入参考。