When to Use a Kinematic Body in Planck.js?
In game development using Planck.js (a 2D physics engine for JavaScript), choosing the right body type is crucial for performance and gameplay mechanics. This article provides a quick overview of when to use a kinematic body instead of static or dynamic bodies. Kinematic bodies are ideal for objects that need to move according to precise script logic or animations—such as moving platforms, elevators, or predictable hazards—while still being able to push dynamic objects out of their way.
Understanding Body Types in Planck.js
To understand when to use a kinematic body, it helps to contrast it with the other two primary body types in Planck.js:
- Static Bodies: Do not move and have zero velocity. They do not collide with other static or kinematic bodies.
- Dynamic Bodies: Fully simulated by the physics engine. They respond to forces, gravity, and collisions.
- Kinematic Bodies: A hybrid type. They move based on user-defined velocity but are not affected by forces or gravity.
Ideal Use Cases for Kinematic Bodies
You should opt for a kinematic body when you want full manual control over an object’s movement, but still need it to interact physically with the player or other dynamic objects.
- Moving Platforms and Elevators: In a platformer game, a moving platform needs to follow a strict path regardless of how many dynamic characters jump on top of it. A dynamic body would sink under the weight, while a static body cannot move. A kinematic body moves exactly as programmed and carries dynamic bodies along with it.
- Predictable Obstacles and Hazards: Moving blades, swinging pendulums (where speed must be constant), or sliding walls that follow a set pattern are perfect candidates.
- User-Controlled Characters (Alternative Approach): While many developers use dynamic bodies for characters, some prefer kinematic bodies to avoid the “floatiness” of physics simulations, allowing for pixel-perfect, deterministic controller inputs.
Key Behaviors of Kinematic Bodies
Before implementing a kinematic body, keep these engine behaviors in mind:
- Velocity-Driven: You move them by setting their
linear velocity (
setLinearVelocity) or angular velocity (setAngularVelocity), not by applying forces or changing their position coordinates directly every frame. - One-Way Collisions: Kinematic bodies will collide with and push dynamic bodies. However, they pass right through static bodies and other kinematic bodies without any collision response.
- Infinite Mass: Effectively, they behave as if they have infinite mass. No amount of force from a dynamic body can slow down, deflect, or stop a kinematic body.