pyxen.world.destroy()
销毁一个现有的 Entity 并将其从世界中移除。
这将永久删除实体及其所有组件。
语法
pyxen.world.destroy(entity)
参数
| 参数 | 类型 | 描述 |
|---|---|---|
entity | Entity | 要销毁的实体。 |
返回值
None
销毁实体时会发生什么
调用 destroy() 将会:
- 从世界中移除该实体
- 移除所有附加的组件(Sprite、Sound、Music、GridMap、GridBody 等)
- 移除父子关系
- 释放其内部 ID 以供复用(代际安全)
销毁后,该实体不应再被使用。
示例
销毁实体
enemy = pyxen.world.spawn(sprite=assets.enemy, x=40, y=12)
# 稍后……
pyxen.world.destroy(enemy)
从游戏逻辑中销毁
if player.health <= 0:
pyxen.world.destroy(player)
常见模式:定时移除
explosion = pyxen.world.spawn(sprite=assets.explosion, x=32, y=16)
if explosion_timer.finished():
pyxen.world.destroy(explosion)
重要注意事项
不要复用已销毁的实体
一旦销毁:
pyxen.world.destroy(enemy)
enemy.x = 10 # 无效用法
该实体在世界中不再有效。
如果你需要一个新实体——再次调用 spawn()。
父子行为
如果被销毁的实体:
- 有子实体 → 它们会被自动移除
- 有父实体 → 它会从层级中移除
销毁是递归且安全的。
类型安全
如果传入非 Entity 对象:
pyxen.world.destroy("not an entity")
将会发生运行时错误。
请始终传入有效的 Entity。
设计理念
在 Pyxen 中:
- 实体是轻量级句柄
- 组件定义行为
- 销毁会移除完整的组合
这使内存可预测且对 ECS 友好。