-
-
Notifications
You must be signed in to change notification settings - Fork 660
Adding a Physic Body to a Renderable
Olivier Biot edited this page Apr 5, 2026
·
6 revisions
To enable interaction between a renderable and the physics world, a Body can be added to any Renderable:
import { Body, Rect, Renderable } from "melonjs";
class Player extends Renderable {
constructor(x, y) {
super(x, y, 32, 48);
// add a physic body
this.body = new Body(this);
// add a rectangular collision shape matching the renderable size
this.body.addShape(new Rect(0, 0, this.width, this.height));
// configure max speed and friction
this.body.setMaxVelocity(3, 15);
this.body.setFriction(0.4, 0);
// enable gravity and collision response
this.isKinematic = false;
}
update(dt) {
// apply a horizontal force (e.g. move right)
this.body.force.x = 3;
return super.update(dt);
}
}- melonJS automatically updates body physics and checks for collisions with other objects in the scene graph.
- The body's velocity, gravity, and friction are applied each frame during the world update.
- Collision detection uses the shapes attached to the body (see Collision Shapes).
- Override
onCollision(response, other)to handle collision responses.
A body can have multiple shapes for complex hitboxes:
import { Body, Rect, Ellipse } from "melonjs";
this.body = new Body(this);
this.body.addShape(new Rect(0, 10, 32, 38)); // main body
this.body.addShape(new Ellipse(16, 5, 20, 10)); // headSet the body's collision type to control what it collides with:
import { collision } from "melonjs";
this.body.collisionType = collision.types.PLAYER_OBJECT;Available types: PLAYER_OBJECT, NPC_OBJECT, ENEMY_OBJECT, COLLECTABLE_OBJECT, ACTION_OBJECT, PROJECTILE_OBJECT, WORLD_SHAPE, USER.