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

如何在Ursina游戏引擎中实现按下指定按键触发的游戏同步计时器

问题原因

Ursina 引擎的渲染、输入检测、逻辑更新全部运行在主线程的帧循环中,直接使用 sleep 类阻塞方法会暂停整个循环的运行,自然会出现程序冻结无响应的问题。另外你现有代码末尾的 input('tab') 是错误的控制台输入调用,也会导致程序启动就卡住等待输入,需要直接删除。

实现方案

用 Ursina 内置的非阻塞延迟调度方法 invoke() 处理60秒计时,搭配全局状态变量控制挑战的启停即可。

修改步骤
  1. 新增全局状态变量,标记挑战是否正在运行、控制积分是否生效
  2. 新增挑战结束回调函数,计时到点后自动触发,停止计分
  3. 修改tab键触发逻辑,按下时重置积分、启动挑战、设置60秒后自动结束挑战
  4. 修改目标刷新的计分逻辑,只有挑战进行中点击目标才累加积分
完整可运行代码
# -*- coding: utf-8 -*-
"""
Created on Tue Oct  5 16:46:24 2021
@author: gf112234
"""
import random
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController

# 新增全局状态变量
game_active = False
challenge_time = 60

##########
# update #
##########
def update():
    # 如果需要显示实时倒计时,可以在这里加UI更新逻辑
    pass

# 新增挑战结束函数
def end_challenge():
    global game_active
    game_active = False
    # 这里可以加挑战结束后的逻辑,比如弹出得分提示
    print(f"挑战结束!你的得分:{points}")

#########
# start #
#########
def targetspawn():
    xpos = random.randrange(-10,10)
    ypos = random.randrange(-6,6)
    zpos = random.randrange(17,20)
    return xpos, ypos, zpos
points = -3
def spawn():
    global points
    # 只有挑战进行中才加分
    if game_active:
        points += 1
    xpos, ypos, zpos = targetspawn()
    target1.position=(xpos, ypos, zpos)
def spawn2():
    global points
    if game_active:
        points += 1
    xpos, ypos, zpos = targetspawn()
    target2.position=(xpos, ypos, zpos)
def spawn3():
    global points
    if game_active:
        points += 1
    xpos, ypos, zpos = targetspawn()
    target3.position=(xpos, ypos, zpos)

def input(key):
    if key == 'tab':
        global points, game_active
        points = 0
        game_active = True
        print("挑战开始!")
        # 60秒后调用end_challenge函数,非阻塞
        invoke(end_challenge, delay=challenge_time)

######################
# Application Window #
######################
app = Ursina()

window.title = 'Static-Click 3 Targets'
window.borderless = False
window.fullscreen = True
mouse.locked = True


ground = Entity(model='plane', scale=(2,1,1), color=color.blue, collider='box')


crosshair = Entity(parent=camera.ui, model='quad', color=color.pink, scale=0.007, rotation_z=45)

player = FirstPersonController(y=0, origin_y=0, mouse_sensitivity=(10,10))

target1 = Button(parent=scene, model='sphere', color=color.blue, position=(0 ,0, 0), collider='sphere')

spawn()

target2 = Button(parent=scene, model='sphere', color=color.red, position=(0 ,0, 0), collider='sphere')

spawn2()

target3 = Button(parent=scene, model='sphere', color=color.yellow, position=(0 ,0, 0), collider='sphere')

spawn3()

target1.on_click = spawn
target2.on_click = spawn2
target3.on_click = spawn3

app.run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:54:00