coeng

view src/gobj.cc @ 5:0e5da17d589c

decided to really work on this, so first a slight rename
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 14 Feb 2015 01:35:42 +0200
parents src/gameobj.cc@4a1c9597f4d3
children 2f872a179914
line source
1 #include <stdio.h>
2 #include <algorithm>
3 #include "gobj.h"
5 GameObject::GameObject()
6 {
7 sorted = true;
8 }
10 GameObject::~GameObject()
11 {
12 for(size_t i=0; i<comp.size(); i++) {
13 delete comp[i];
14 }
15 }
17 bool GameObject::add_component(Component *c)
18 {
19 const char *name = c->get_name();
21 if(comp_by_name.find(name) != comp_by_name.end()) {
22 fprintf(stderr, "component %s already exists in this game object (%p)\n", name, (void*)this);
23 return false;
24 }
26 try {
27 comp.push_back(c);
28 comp_by_name[name] = c;
30 c->gobj = this;
31 }
32 catch(...) {
33 fprintf(stderr, "failed to add component: %s\n", name);
34 return false;
35 }
37 sorted = false;
38 return true;
39 }
41 bool GameObject::remove_component(Component *c)
42 {
43 for(size_t i=0; i<comp.size(); i++) {
44 if(comp[i] == c) {
45 comp.erase(comp.begin() + i);
46 comp_by_name.erase(c->get_name());
47 return true;
48 }
49 }
50 return false;
51 }
53 bool GameObject::delete_component(Component *c)
54 {
55 if(remove_component(c)) {
56 delete c;
57 return true;
58 }
59 return false;
60 }
62 Component *GameObject::get_component(const char *name) const
63 {
64 std::map<std::string, Component*>::const_iterator it;
65 if((it = comp_by_name.find(name)) != comp_by_name.end()) {
66 return it->second;
67 }
68 return 0;
69 }
71 void GameObject::update()
72 {
73 if(!sorted) {
74 std::sort(comp.begin(), comp.end());
75 }
77 for(size_t i=0; i<comp.size(); i++) {
78 comp[i]->update();
79 }
80 }