You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ursina框架时按Esc键程序冻结问题求助

Ursina框架按下Esc键退出游戏时程序冻结的解决方法

问题出在你用update()函数结合held_keys['escape']检测按键的方式上:update()每帧都会执行,按住Esc时held_keys['escape']会持续返回True,导致application.quit()被反复调用,干扰了程序的正常退出流程,最终引发冻结。

Ursina推荐使用input()函数处理单次按键事件,它只会在按键按下的瞬间触发一次,能避免重复调用退出逻辑。

修改后的代码如下:

from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()

class Voxel(Button):
    def __init__(self, position=(0, 0, 0)):
        super().__init__(
            parent=scene,
            position=position,
            model='cube',
            origin_y=0.5,
            texture='white_cube',
            color=color.color(0, 0, random.uniform(0.9, 1.0)),
            highlight_color=color.lime
        )

    def input(self, key):
        if self.hovered:
            if key == 'left mouse down':
                voxel = Voxel(position=self.position + mouse.normal)
            if key == 'right mouse down':
                destroy(self)

# 替换原update函数为input函数,处理单次按键事件
def input(key):
    if key == 'escape':
        print("Escape key pressed")
        application.quit()

for z in range(8):
    for x in range(8):
        voxel = Voxel(position=(x, 0, z))

player = FirstPersonController()
app.run()

如果坚持要用held_keys的方式,也可以通过添加标记变量确保退出逻辑只执行一次:

quit_triggered = False

def update():
    global quit_triggered
    if held_keys['escape'] and not quit_triggered:
        quit_triggered = True
        print("Escape key pressed")
        application.quit()

但这种方式不如直接使用input()函数简洁直观。

内容的提问来源于stack exchange,提问作者user21014068

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 06:36:02