coeng
view src/gameobj.cc @ 1:b0d8d454c546
foo
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Thu, 05 Feb 2015 00:38:59 +0200 |
parents | |
children | 4a1c9597f4d3 |
line source
1 #include <algorithm>
2 #include "gameobj.h"
4 GameObject::GameObject()
5 {
6 sorted = true;
7 }
9 GameObject::~GameObject()
10 {
11 for(size_t i=0; i<comp.size(); i++) {
12 delete comp[i];
13 }
14 }
16 bool GameObject::add_component(Component *c)
17 {
18 const char *name = c->get_name();
20 if(comp_by_name.find(name) != comp_by_name.end()) {
21 fprintf(stderr, "component %s already exists in this game object (%p)\n", name, (void*)this);
22 return false;
23 }
25 try {
26 comp.push_back(c);
27 comp_by_name[name] = c;
28 }
29 catch(...) {
30 fprintf(stderr, "failed to add component: %s\n", name);
31 return false;
32 }
34 sorted = false;
35 return true;
36 }
38 bool GameObject::remove_component(Component *c)
39 {
40 for(size_t i=0; i<comp.size(); i++) {
41 if(comp[i] == c) {
42 comp.erase(comp.begin() + i);
43 comp_by_name.erase(c->get_name());
44 return true;
45 }
46 }
47 return false;
48 }
50 bool GameObject::delete_component(Component *c)
51 {
52 if(remove_component(c)) {
53 delete c;
54 return true;
55 }
56 return false;
57 }
59 Component *GameObject::get_component(const char *name) const
60 {
61 std::map<std::string, Component*>::const_iterator it;
62 if((it = comp_by_name.find(name)) != comp_by_name.end()) {
63 return it->second;
64 }
65 return 0;
66 }
68 void GameObject::update()
69 {
70 if(!sorted) {
71 std::sort(comp.begin(), comp.end());
72 }
74 for(size_t i=0; i<comp.size(); i++) {
75 comp[i]->update();
76 }
77 }