Skip to content
Olivier Biot edited this page Feb 11, 2014 · 9 revisions

since version 1.0.0, melonJS introduced the concept of Collision shape, that replaced the old collisionBox implementation by a more generic and flexible API.

A collision shape is either a me.Rect, me.Ellipse or me.PolyShape object attached to the object entity, and (when using Tiled), a collision Shape is automatically added to your entity based on the object size and shape defined in Tiled.

Collision shape can also be manually managed through the following functions :

  • addShape() to add a new shape to your objects
  • setShape() to set the default shape to be used for collision
  • getShape() to get the current collision shape (also used internally by the engine)

Shape object are now also relative to their parent object (here an entity), which means that by default their position vector is (0, 0)

Additionally Shape objects also define a getBounds function that can be used to get the corresponding bounding box (rectangle) of that Shape, that is useful most of all when managing non rectangular shape (melonJS uses this internally to define to calculate the collision using AABB for now, generate the quadtree in the ticket-103 branch, or identify which objects has been clicked).

Usage example

Let's take the example where for any reason we need to know the size of the object collision shape :

  • Previous Implementation (melonJS 0.9.x) :
var size = entity.collisionBox.width;
  • Shape Implementation (melonJS 1.x.x)
var size = entity.getShape().width;

if you now not only use rectangular shapes, the safest path is to use the getBounds() function

var size = entity.getShape().getBounds().width;

Finally, note that getBounds() also takes as a parameter an optional rectangle object that can be useful is you repeatedly call this function, as getBounds() returns a new rectangle object on each call.

// somewhere in your constructor
this.cacheBounds = new me.Rect(new me.Vector2d(), 0, 0);
....
// anywhere else in your code (or also in the constructor if do not change the collion shape size)
this.cacheBounds = entity.getShape().getBounds(this.cacheBounds).width;
// get the collision shape size
var size = this.cacheBounds.width;

At the end yes it's a bit more complex, but we do however have now a very flexible API that can transparently manage any kind of shape !