如何在Python Ursina中获取鼠标位置向量并解决数组为空问题
解决Ursina平台编辑器中平台位置数组为空的问题
我正在制作一个平台编辑器,需要获取鼠标位置并在该位置放置平台对象,之后要将鼠标的Vector3位置存储到数组中,以便后续转换为代码。但目前执行存储操作时,得到的是空数组。
原代码
from ursina import * from ursina.prefabs.sky import Sky from ursina.shaders import basic_lighting_shader app = Ursina(borderless = False) window.fullscreen = True window.fps_counter.enabled = False editor = EditorCamera() camera.fov = 90 class StartPlatform(Entity): def __init__(self): super().__init__( parent = scene, model = "cube", position = (0, 0, 0), scale = (10, 2, 10), collider = "mesh", shader = basic_lighting_shader, texture = "white_cube", color = color.lime ) class AddPlatform(Entity): def __init__(self, position = (0, 0, 0)): super().__init__( parent = scene, model = "cube", position = position, scale = (10, 2, 10), collider = "mesh", shader = basic_lighting_shader, texture = "white_cube", color = color.azure ) def input(key): if held_keys["escape"]: quit() def update(): if held_keys["left mouse"]: platform= AddPlatform(position = (mouse.world_point, mouse.world_point, mouse.world_point)) platforms = [] for i in platforms: platform[i].append(platforms) print(platforms) Sky() StartPlatform() app.run()
问题原因
- 数组重复初始化:
platforms = []写在update()函数内部,每次鼠标点击都会重新创建空数组,之前存储的位置全部丢失。 - 位置参数错误:
mouse.world_point本身就是Ursina的Vector3类型,无需拆分为三个相同值传入,这样会导致位置赋值错误。 - 存储逻辑混乱:循环空数组没有实际意义,且
platform[i].append(platforms)的写法完全错误,平台对象不支持下标访问,也不该将数组本身添加进去。
修复后的代码
from ursina import * from ursina.prefabs.sky import Sky from ursina.shaders import basic_lighting_shader app = Ursina(borderless = False) window.fullscreen = True window.fps_counter.enabled = False editor = EditorCamera() camera.fov = 90 # 全局数组存储平台位置,避免每次点击重置 platform_positions = [] class StartPlatform(Entity): def __init__(self): super().__init__( parent = scene, model = "cube", position = (0, 0, 0), scale = (10, 2, 10), collider = "mesh", shader = basic_lighting_shader, texture = "white_cube", color = color.lime ) # 可选:将初始平台位置加入数组 platform_positions.append(self.position) class AddPlatform(Entity): def __init__(self, position = (0, 0, 0)): super().__init__( parent = scene, model = "cube", position = position, scale = (10, 2, 10), collider = "mesh", shader = basic_lighting_shader, texture = "white_cube", color = color.azure ) def input(key): if key == "escape": quit() # 用单次点击事件替代持续检测,避免重复创建平台 if key == "left mouse down": # 直接传入mouse.world_point作为平台位置 new_platform = AddPlatform(position=mouse.world_point) # 将新平台的位置存入数组 platform_positions.append(new_platform.position) print("当前存储的平台位置:", platform_positions) Sky() StartPlatform() app.run()
关键修改点
- 把存储位置的数组定义为全局变量,确保数据不会被重置。
- 改用
input()事件处理鼠标左键单次点击,避免按住鼠标时持续创建平台和重复存储位置。 - 修正平台位置的参数传递,直接使用
mouse.world_point。 - 调整存储逻辑,将新平台的
position属性正确添加到数组中。
内容的提问来源于stack exchange,提问作者DonYeet46
相关产品推荐
相关产品推荐

