使用Ursina开发沙盒游戏时无法看到放置的方块问题求助
Ursina沙盒游戏木方块不显示问题排查与修复
问题分析
你遇到的木方块不显示(包括颜色、纹理均无效)的问题,大概率是以下几个原因之一:
- 纹理路径错误导致加载失败,进而影响方块渲染
- 颜色字符串未被Ursina正确识别
- 碰撞体未显式设置(虽然原方块正常,但新方块可能存在交互异常)
- 遍历方块列表时的潜在迭代问题(左键删除会影响遍历,间接导致右键添加的逻辑异常)
修复步骤
修正纹理路径
确保texture/wood.jpg文件存在于项目根目录的texture文件夹中。如果纹理直接放在根目录,将路径改为'wood.jpg'。如果暂时不想用纹理,可先注释掉texture参数,单独测试颜色是否生效。替换颜色为Ursina内置常量
将color="brown"改为color=color.brown,Ursina对字符串颜色的支持有限,使用内置color类的常量能确保颜色正确应用:def add_box_wood(position): boxes.append( Button( parent=scene, model="cube", origin=0.5, color=color.brown, position=position, texture='texture/wood.jpg' ) )显式添加碰撞体
给Button添加collider='box'参数,确保方块能被正确检测hover和交互,同时避免渲染异常:def add_box_wood(position): boxes.append( Button( parent=scene, model="cube", origin=0.5, color=color.brown, position=position, texture='texture/wood.jpg', collider='box' ) )同时建议给
add_box函数的Button也加上该参数,保持一致性。修复列表遍历问题
在input函数中,遍历boxes时使用副本(boxes[:]),避免左键删除方块时修改原列表导致的遍历异常:def input(key): # 遍历列表副本,防止删除元素时打断迭代 for box in boxes[:]: if box.hovered: if key == "right mouse down": add_box_wood(box.position + mouse.normal) if key == "left mouse down": boxes.remove(box) destroy(box)调试位置有效性
在add_box_wood函数中添加打印语句,确认方块被添加到可见位置:def add_box_wood(position): print(f"添加木方块到位置:{position}") boxes.append( # ... 其余代码 ... )如果位置在地下(比如y值小于-4),调整点击逻辑或检查
mouse.normal的方向是否正确。
完整修复后代码
from ursina import * from ursina.prefabs.first_person_controller import FirstPersonController app = Ursina() player = FirstPersonController() Sky() boxes = [] def add_box(position): boxes.append( Button( parent=scene, model="cube", origin=0.5, color="green", position=position, texture="grass", collider='box' ) ) def add_box_wood(position): print(f"添加木方块到位置:{position}") boxes.append( Button( parent=scene, model="cube", origin=0.5, color=color.brown, position=position, texture='texture/wood.jpg', collider='box' ) ) for x in range(20): for y in range(20): add_box( (x, -4, y) ) def input(key): for box in boxes[:]: if box.hovered: if key == "right mouse down": add_box_wood(box.position + mouse.normal) if key == "left mouse down": boxes.remove(box) destroy(box) app.run()
内容的提问来源于stack exchange,提问作者Funny_Gurke
相关产品推荐
相关产品推荐

