如何在Python Ursina引擎中实现场景切换功能
Ursina 场景切换最简实现方案
自定义Scene类传参报错通常是未正确调用父类初始化方法,或parent参数赋值不符合Scene类的内置校验规则。以下方案可以直接复现滑入滑出的场景切换效果,无需使用内置Scene类,实现更灵活:
- 直接用
Entity作为每个场景的根节点,Ursina的Scene本质就是实体容器,用Entity实现可以避开Scene类的额外校验逻辑,是社区更常用的场景管理方案 - 给每个场景根节点设置初始位置在屏幕外,切换时调用内置
animate方法做位移动画,即可实现和参考效果一致的滑入滑出体验
完整可运行代码示例:
from ursina import * # 主菜单场景 class MainMenu(Entity): def __init__(self): super().__init__() # 初始放在屏幕左侧外 self.x = -16 # 场景内元素 Text(parent=self, text="主菜单", y=0.3, scale=3) Button(parent=self, text="进入游戏", y=0, scale=0.1, on_click=switch_to_game) # 游戏场景 class GameScene(Entity): def __init__(self): super().__init__() # 初始放在屏幕右侧外 self.x = 16 # 场景内元素 Text(parent=self, text="游戏场景", y=0.3, scale=3) Button(parent=self, text="返回主菜单", y=0, scale=0.1, on_click=switch_to_menu) current_scene = None def switch_to_game(): global current_scene # 旧场景向左滑出 animate(current_scene, 'x', -16, duration=0.3, curve=curve.ease_in_out) # 新场景从右滑入 animate(game_scene, 'x', 0, duration=0.3, curve=curve.ease_in_out) current_scene = game_scene def switch_to_menu(): global current_scene # 旧场景向右滑出 animate(current_scene, 'x', 16, duration=0.3, curve=curve.ease_in_out) # 新场景从左滑入 animate(menu_scene, 'x', 0, duration=0.3, curve=curve.ease_in_out) current_scene = menu_scene if __name__ == "__main__": app = Ursina() # 预创建所有场景 menu_scene = MainMenu() game_scene = GameScene() # 默认加载主菜单 current_scene = menu_scene animate(current_scene, 'x', 0, duration=0.3) app.run()
额外调整说明:
- 如果需要上下切换效果,把代码里的x属性替换为y,初始位置改为
y=±9即可 duration参数控制动画时长,curve参数控制缓动效果,可根据需求自行调整
内容的提问来源于stack exchange,提问作者Jeremie Tanguay
相关产品推荐
相关产品推荐

