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

Ursina引擎使用FirstPersonController时如何正常通过鼠标关闭窗口

你遇到的窗口无法正常关闭的问题,确实是FirstPersonController预制体的默认行为导致的:该控制器为了实现第一人称视角的鼠标转向操作,默认会将鼠标锁定在游戏窗口内部,因此无法直接移动鼠标到窗口外点击关闭按钮。

解决方案

这里提供两种常用的实现方案,可根据需求选择:

方案1:添加ESC快捷键直接关闭窗口

这是最便捷的处理方式,玩家按下ESC键即可直接退出游戏,不需要额外操作。只需要在game.run()之前添加如下代码即可:

def input(key):
    if key == 'escape':
        # 调用Ursina内置的退出方法
        application.quit()

方案2:按ESC切换鼠标锁定状态

如果你希望保留手动点击关闭按钮的操作逻辑,可以设置按下ESC键解锁/锁定鼠标,解锁后即可自由移动鼠标点击关闭按钮,需要操作游戏时再按下ESC重新锁定鼠标即可:

def input(key):
    if key == 'escape':
        # 切换鼠标的锁定状态
        mouse.locked = not mouse.locked

修改后的完整示例代码

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

game = Ursina()

class Block(Button):
    def __init__(self, position = (0,0,0)):
        super().__init__(parent = scene, position = position, model = 'cube', color = color.white)

for z in range(20):
    for x in range(20):
        block = Block(position = (x, 0, z))

player = FirstPersonController()

# 这里使用方案1的直接退出逻辑,可自行替换为方案2
def input(key):
    if key == 'escape':
        application.quit()

game.run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:24:03