Skip to content

Commit

Permalink
Correção da adição/remoção de filhos.
Browse files Browse the repository at this point in the history
  • Loading branch information
edsomjr committed Jun 4, 2016
1 parent ef298e3 commit b81ba32
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
6 changes: 6 additions & 0 deletions include/game_object.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ namespace ijengine {

void add_child(GameObject *obj);
void remove_child(GameObject *obj);
void destroy_child(GameObject *obj);

double x() const;
double y() const;
GameObject * parent() const { return m_parent; }

void set_x(double value) { m_x = value; }
void set_y(double value) { m_y = value; }
Expand All @@ -36,11 +38,15 @@ namespace ijengine {

int priority() const { return m_priority; }

bool valid() const { return m_valid; }
void invalidate() { m_valid = false; }

protected:
GameObject *m_parent;
vector<GameObject *> m_children;
double m_x, m_y;
int m_priority;
bool m_valid;

virtual void update_self(unsigned now, unsigned last) = 0;
virtual void draw_self(Canvas *canvas, unsigned now, unsigned last) = 0;
Expand Down
53 changes: 47 additions & 6 deletions src/game_object.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ using std::stable_sort;
namespace ijengine {

GameObject::GameObject(GameObject *obj, double xpos, double ypos,
int p) : m_parent(obj), m_x(xpos), m_y(ypos),
m_priority(p)
int p) : m_parent(nullptr), m_x(xpos), m_y(ypos),
m_priority(p), m_valid(true)
{
if (m_parent)
m_parent->update_priorities();
if (obj)
{
obj->add_child(this);
}
}

GameObject::~GameObject()
Expand All @@ -23,10 +25,36 @@ namespace ijengine {
void
GameObject::add_child(GameObject *obj)
{
if (obj != this)
m_children.push_back(obj);
if (not obj)
return;

auto p = obj->parent();

if (p)
{
if (p != this)
p->remove_child(obj);
else
return;
}

m_children.push_back(obj);
obj->set_parent(this);
update_priorities();

printf("%p added to %p\n", (void *) obj, (void *) this);

printf("children:");
for (auto child : m_children)
printf(" %p", (void *) child);
printf("\n");
}

void
GameObject::destroy_child(GameObject *obj)
{
remove_child(obj);
delete obj;
}

void
Expand All @@ -37,6 +65,13 @@ namespace ijengine {
obj->set_parent(nullptr);
m_children.erase(remove(m_children.begin(), m_children.end(), obj));
update_priorities();
printf("%p removed from %p\n", (void *) obj, (void *) this);

printf("children:");
for (auto child : m_children)
printf(" %p", (void *) child);
printf("\n");

}
}

Expand Down Expand Up @@ -80,6 +115,12 @@ namespace ijengine {
child->update(now, last);

update_self(now, last);

for (size_t i = 0; i < m_children.size(); ++i)
if (not m_children[i]->valid())
{
destroy_child(m_children[i]);
}
}

void
Expand Down

0 comments on commit b81ba32

Please sign in to comment.