coeng
diff 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 diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/gameobj.cc Thu Feb 05 00:38:59 2015 +0200 1.3 @@ -0,0 +1,77 @@ 1.4 +#include <algorithm> 1.5 +#include "gameobj.h" 1.6 + 1.7 +GameObject::GameObject() 1.8 +{ 1.9 + sorted = true; 1.10 +} 1.11 + 1.12 +GameObject::~GameObject() 1.13 +{ 1.14 + for(size_t i=0; i<comp.size(); i++) { 1.15 + delete comp[i]; 1.16 + } 1.17 +} 1.18 + 1.19 +bool GameObject::add_component(Component *c) 1.20 +{ 1.21 + const char *name = c->get_name(); 1.22 + 1.23 + if(comp_by_name.find(name) != comp_by_name.end()) { 1.24 + fprintf(stderr, "component %s already exists in this game object (%p)\n", name, (void*)this); 1.25 + return false; 1.26 + } 1.27 + 1.28 + try { 1.29 + comp.push_back(c); 1.30 + comp_by_name[name] = c; 1.31 + } 1.32 + catch(...) { 1.33 + fprintf(stderr, "failed to add component: %s\n", name); 1.34 + return false; 1.35 + } 1.36 + 1.37 + sorted = false; 1.38 + return true; 1.39 +} 1.40 + 1.41 +bool GameObject::remove_component(Component *c) 1.42 +{ 1.43 + for(size_t i=0; i<comp.size(); i++) { 1.44 + if(comp[i] == c) { 1.45 + comp.erase(comp.begin() + i); 1.46 + comp_by_name.erase(c->get_name()); 1.47 + return true; 1.48 + } 1.49 + } 1.50 + return false; 1.51 +} 1.52 + 1.53 +bool GameObject::delete_component(Component *c) 1.54 +{ 1.55 + if(remove_component(c)) { 1.56 + delete c; 1.57 + return true; 1.58 + } 1.59 + return false; 1.60 +} 1.61 + 1.62 +Component *GameObject::get_component(const char *name) const 1.63 +{ 1.64 + std::map<std::string, Component*>::const_iterator it; 1.65 + if((it = comp_by_name.find(name)) != comp_by_name.end()) { 1.66 + return it->second; 1.67 + } 1.68 + return 0; 1.69 +} 1.70 + 1.71 +void GameObject::update() 1.72 +{ 1.73 + if(!sorted) { 1.74 + std::sort(comp.begin(), comp.end()); 1.75 + } 1.76 + 1.77 + for(size_t i=0; i<comp.size(); i++) { 1.78 + comp[i]->update(); 1.79 + } 1.80 +}