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