Collision 2D Game


hi guys, it’s me again with my 2D game.
I have to implement the collisions, and I wanted to ask you if Cinder implemented the collisions between 2 TextureRef because I thought to check with each movement all the TextureRef present in my window to know if it was in collision with my character, is it the right way to do?


Collision detection and response should be completely separate from your rendering, i.e your gl::TextureRefs only display what your collision system already determined your entities’ locations to be. If it’s a 2D game, would you classify it as being tile based? If so, here’s a couple of tutorials you can look at that will hopefully get you started.


It would not perform very well to check 2 textures pixel by pixel whether they collide. It’s better to use a simplified version of your character to check collisions. The simplest I can think of is using the rectangle, aligned with the x and y axes (so the texture has not been rotated).

Cinder has a Rectf class that can help you out a bit. You can obtain the bounds of the texture like this:

auto bounds = mTexture->getBounds(); // returns Rectf( 0, 0, width, height );

You should then apply the transformations of your character (scale, position and anchor, the latter being the point on the texture you use as your origin) to the bounds to calculate its bounds in the window:

// Combine all transformation into a single matrix:
auto transform = glm::translate( mPosition ) * glm::scale( mScale ) 
                     * glm::translate( -mAnchor );
// Apply it to the bounds:
bounds.transform( transform );

Do that for the other character as well. And then you can do this:

if( bounds.intersects( enemy ) )
    app::console() << "I'm hit!" << std::endl;

Apart from Rectf, Cinder also has a Circle class that can help you out. For 3D games, we have AxisAlignedBox and Sphere. If you need more than that (e.g. collision detection between two arbitrary polygons, cones, cylinders, etc.), you better start looking for a nice 2D or 3D physics engine.


P.S.: for polygons, you could use the PolyLine class. It has a contains( vec2 ) method to check if a point is inside the polygon.


thanks guys i’ll implement that.
I’ll keep you informed