add entity.despawn(...)

This commit is contained in:
MihailRis 2024-06-27 14:26:51 +03:00
parent 6d7f950410
commit e11760a5e4
4 changed files with 40 additions and 3 deletions

View File

@ -40,6 +40,7 @@ void LevelController::update(float delta, bool input, bool pause) {
level->objects.end()
);
level->entities->clean();
if (!pause) {
// update all objects that needed
for (const auto& obj : level->objects) {

View File

@ -31,6 +31,13 @@ static int l_spawn(lua::State* L) {
return lua::pushinteger(L, id);
}
static int l_despawn(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
entity->destroy();
}
return 0;
}
static int l_get_pos(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
return lua::pushvec3_arr(L, entity->getTransform().pos);
@ -87,8 +94,16 @@ static int l_set_enabled(lua::State* L) {
return 0;
}
static int l_get_size(lua::State* L) {
if (auto entity = get_entity(L, 1)) {
return lua::pushvec3(L, entity->getRigidbody().hitbox.halfsize * 2.0f);
}
return 0;
}
const luaL_Reg entitylib [] = {
{"spawn", lua::wrap<l_spawn>},
{"despawn", lua::wrap<l_despawn>},
{NULL, NULL}
};
@ -105,5 +120,6 @@ const luaL_Reg rigidbodylib [] = {
{"set_enabled", lua::wrap<l_set_enabled>},
{"get_vel", lua::wrap<l_get_vel>},
{"set_vel", lua::wrap<l_set_vel>},
{"get_size", lua::wrap<l_get_size>},
{NULL, NULL}
};

View File

@ -33,6 +33,16 @@ entityid_t Entities::spawn(EntityDef& def, glm::vec3 pos) {
return id;
}
void Entities::clean() {
for (auto it = entities.begin(); it != entities.end(); ++it) {
if (registry.valid(it->second)) {
++it;
} else {
it = entities.erase(it);
}
}
}
void Entities::updatePhysics(float delta){
auto view = registry.view<Transform, Rigidbody>();
auto physics = level->physics.get();

View File

@ -36,11 +36,16 @@ class Rig;
struct EntityDef;
class Entity {
entityid_t id;
entt::registry& registry;
const entt::entity entity;
public:
Entity(entt::registry& registry, const entt::entity entity)
: registry(registry), entity(entity) {}
Entity(entityid_t id, entt::registry& registry, const entt::entity entity)
: id(id), registry(registry), entity(entity) {}
entityid_t getID() const {
return id;
}
bool isValid() const {
return registry.valid(entity);
@ -57,6 +62,10 @@ public:
entityid_t getUID() const {
return registry.get<EntityId>(entity).uid;
}
void destroy() {
registry.destroy(entity);
}
};
class Entities {
@ -66,6 +75,7 @@ class Entities {
entityid_t nextID = 1;
public:
Entities(Level* level);
void clean();
void updatePhysics(float delta);
void renderDebug(LineBatch& batch);
@ -76,7 +86,7 @@ public:
std::optional<Entity> get(entityid_t id) {
const auto& found = entities.find(id);
if (found != entities.end()) {
return Entity(registry, found->second);
return Entity(id, registry, found->second);
}
return std::nullopt;
}