Phaser 3中禁用多键冲突:按下其他键时保持角色移动(不使用update)
解决Phaser 3中按住箭头键移动时,按下其他键不中断移动的问题(无需update方法)
问题根源
你当前使用全局keydown事件触发单次tween移动,一旦按下其他按键,可能因事件触发逻辑或tween的单次执行特性导致移动中断。要实现按住箭头键持续移动且不受其他按键影响,需单独监听目标按键的按下/松开事件,并使用循环tween维持移动状态。
实现方案
- 单独监听右箭头键的
keydown和keyup事件,避免全局事件干扰 - 用无限重复的tween实现持续移动,按下按键时启动tween,松开时停止
修改后的代码示例
// 在场景的create方法中初始化键盘监听 create() { // 初始化角色(示例) this.car = this.add.sprite(100, 300, 'car'); // 监听右箭头键按下事件 this.input.keyboard.on('keydown-ArrowRight', () => { // 避免重复启动tween if (!this.carMoveTween || !this.carMoveTween.isPlaying()) { this.startContinuousMove(); } }); // 监听右箭头键松开事件 this.input.keyboard.on('keyup-ArrowRight', () => { if (this.carMoveTween && this.carMoveTween.isPlaying()) { this.carMoveTween.stop(); } }); } startContinuousMove() { // 创建无限重复的tween实现持续移动 this.carMoveTween = this.tweens.add({ targets: this.car, x: '+=15', // 每次移动的像素距离 duration: 120, // 单次移动的时长(控制移动速度) ease: 'Linear', repeat: -1, // 无限重复 yoyo: false // 不往返 }); }
关键说明
- 单独监听
keydown-ArrowRight和keyup-ArrowRight,确保只有右箭头键的状态变化会影响移动 - 使用
tween.repeat: -1实现无限循环移动,避免单次tween结束后停止 - 添加tween状态判断,防止重复创建tween导致的冲突
内容的提问来源于stack exchange,提问作者Newboy11
相关产品推荐
相关产品推荐

