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

如何实现按R键重启游戏并将角色重置到地图中央?

解决方案:给Ursina游戏添加R键重置功能

修复基础问题

你的代码里缺少random模块的导入,先补上:

import random

实现按R键重置角色到地图中间

地图是20x20的方块(x和z范围0-19),地图中间位置设为(9.5, 1, 9.5)(y值设为1是避免和地面方块重叠)。在input函数里添加R键的处理逻辑即可:

修改后的input函数:

def input(key):
    # 处理方块的放置与删除
    for box in boxes:
        if box.hovered:
            if key == "right mouse down":
                add_box(box.position + mouse.normal)
            if key == "left mouse down":
                boxes.remove(box)
                destroy(box)
    # 处理R键重置角色位置
    if key == 'r':
        # 重置位置到地图中间
        player.position = (9.5, 1, 9.5)
        # 重置视角朝向
        player.rotation = (0, 0, 0)
        player.camera_pivot.rotation = (0, 0, 0)
    # 处理ESC退出
    if kb.is_pressed("escape"):
        exit()
    # 处理Shift加速
    if kb.is_pressed("shift"):
        player.speed = 15
    else:
        player.speed = 7

实现按R键重启整个游戏

如果需要完全重置游戏(包括恢复所有方块的初始状态),可以使用Ursina内置的app.restart()方法,替换上面的R键逻辑:

if key == 'r':
    app.restart()

app.restart()会重新运行整个游戏程序,所有修改过的方块都会回到初始状态。

完整修改后的代码

import random
import keyboard as kb
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController

app = Ursina()
window.fps_counter.enabled = False
player = FirstPersonController()
Sky()

boxes = []

def random_color():
    red = random.Random().random() * 20
    green = random.Random().random() * 255
    blue = random.Random().random() * 20
    return color.rgb(red, green, blue)

def add_box(position):
    boxes.append(
        Button(
            parent=scene,
            model='cube',
            origin=0.5,
            color=random_color(),
            position=position,
            texture='grass'
        )
    )

for x in range(20):
    for y in range(20):
        add_box( (x, 0, y) )

def input(key):
    for box in boxes:
        if box.hovered:
            if key == "right mouse down":
                add_box(box.position + mouse.normal)
            if key == "left mouse down":
                boxes.remove(box)
                destroy(box)
    # 重置角色位置到中间
    if key == 'r':
        player.position = (9.5, 1, 9.5)
        player.rotation = (0, 0, 0)
        player.camera_pivot.rotation = (0, 0, 0)
        # 如果要重启整个游戏,替换上面三行为:
        # app.restart()
    if kb.is_pressed("escape"):
        exit()
    if kb.is_pressed("shift"):
        player.speed = 15
    else:
        player.speed = 7

app.run()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 13:30:53