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

Ursina设置camera位置/旋转属性后运行无画面问题求助

问题定位

代码里有3个直接导致黑屏/运行异常的问题:

  1. camera.position = () 给相机位置赋值了空元组,属于非法参数。Ursina中相机position属性必须传入x/y/z三轴组成的三维坐标,空值会导致相机位置完全失效,场景无法被渲染。
  2. 代码存在多处缩进错误:类下的create_map、new_game等方法定义缩进量不对,if __name__ == '__main__':块下的执行代码也没有缩进,Python无法正确识别类结构和执行逻辑。
  3. 相机坐标没有对齐网格中心:网格整体放在(MAP_SIZE//2, MAP_SIZE//2, 0)位置,默认相机初始位置是(0,0,-20),就算参数合法,不偏移x/y轴也没法让网格居中。
修复步骤
  • 把camera.position的空元组替换为合法三维坐标,要对准20x20网格中心的话,设为(self.MAP_SIZE//2, self.MAP_SIZE//2, -25)即可,z轴取-25保证视野能覆盖全尺寸网格。
  • 修正所有Python语法缩进:类内部方法相对class关键字缩进4空格,main执行块内的代码相对if判断缩进4空格。
  • 保留camera.rotation_x = 57的斜俯视角设置即可,不需要额外改动旋转参数。
修复后可运行代码
from ursina import *

class Game(Ursina):
    def __init__(self):
        super().__init__()
        window.color = color.black
        window.fullscreen_size = (1920, 1080)
        window.fullscreen = True
        Light(type='ambient', color=(0.5, 0.5, 0.5, 1))
        Light(type='directional', color=(0.5, 0.5, 0.5, 1), direction=(1, 1, 1))
        self.MAP_SIZE = 20
        self.new_game()
        camera.position = (self.MAP_SIZE//2, self.MAP_SIZE//2, -25)
        camera.rotation_x = 57

    def create_map(self, MAP_SIZE):
        Entity(model='quad', scale=MAP_SIZE, position=(MAP_SIZE // 2, MAP_SIZE // 2, 0), color=color.dark_gray)
        Entity(model=Grid(MAP_SIZE, MAP_SIZE), scale=MAP_SIZE, position=(MAP_SIZE // 2, MAP_SIZE // 2, -0.01), color=color.white)

    def new_game(self):
        self.create_map(self.MAP_SIZE)

    def input(self, key):
        super().input(key)

    def update(self):
        pass
    

if __name__ == '__main__':
    game = Game()
    game.run()

注意:Ursina中所有3D空间对象的position属性都必须传入长度为3的数值序列(元组/列表均可),对应x、y、z三个轴向的坐标,传入空值、长度不匹配的序列都会导致位置参数失效,出现无渲染内容的问题。如果需要正俯视视角,把camera.rotation_x改成90即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 04:12:56