Skip to content

Instantly share code, notes, and snippets.

@ryohey
Created January 24, 2014 04:28
Show Gist options
  • Select an option

  • Save ryohey/8592094 to your computer and use it in GitHub Desktop.

Select an option

Save ryohey/8592094 to your computer and use it in GitHub Desktop.
Practical Collision Detection in cocos2d-x v3.0beta0
/**
* The problem is the damage effect that changes boundingBox while detecting collision.
* To detect collision correctly, We need to make lists of collided sprites.
*
* Character Class inherited Node and implemted onCollision method.
*
* class Character: public Node {
* public:
* onCollision(Vector<Character *> *characters);
* }
*
* Wrapping Vector in cocos Object to keep that in Map
*
* class VectorObj: public Object {
* VectorObj() {
* vect = new Vector<T>();
* };
* Vector<T> *vect;
* }
*
*/
// collided character lists for each characters
auto map = new Map<Character *, VectorObj<Character *> *>();
for (auto charaA: *characters) {
Rect rectA = charaA->getBoundingBox();
for (auto charaB: *characters) {
if (charaB != charaA) {
Rect rectB = charaB->getBoundingBox();
if (rectA.intersectsRect(rectB)) {
auto list = map->at(charaA);
// create new vector if the collision list doesn't exist yet
if (list == NULL) {
list = new VectorObj<Character *>();
map->insert(charaA, list);
}
list->vect->pushBack(charaB);
}
}
}
}
for (auto chara: map->keys()) {
chara->onCollision(map->at(chara)->vect);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment