New PhysicsWorld component to set Box2D World properties

I propose a new PhysicsWorld component that could be used to control the global physics properties of the Box2D World class.

This would be similar to having multiple camera components. There would be a default PhysicsWorld component that would have focus, but we could change the PhysicsWorld by sending a message like acquire_world_focus to one of the components in my collection.

The PhysicsWorld would also support a set_world message to set Box2D World properties, such as the gravity (as a vector) and velocity_threshold (as a number).

PhysicsWorld components wouldn’t actually represent different Box2D World instances, since reparenting bodies would be a major hassle. Instead, they could simply represent a list of properties. When switching between two PhysicsWorld objects, the effect would simply be to instantly change the associated properties (gravity and velocity threshold for now, maybe more later).


Stretch Goal
Inspired by Pkeod’s request, would be the ability to set the context of Collision components to different PhysicsWorld components (rather than a single global World), essentially running separate Worlds simultaneously.

Of course, collision objects could only belong to one World at a time, and you probably wouldn’t want to support reparenting a collision object to a different world at runtime. I imagine there would be serious issues with speed, and confusion over why collisions aren’t detected between objects belonging to different worlds, so it’s probably not very practical, but it would enable some cool background effects, etc.

Could you not just use kinematic collision objects and just apply your own gravity to your game objects each frame?

Something like this:

local GRAVITY = -10 -- desired gravity

function update(self, dt)

  local gravity = vmath.vector3(0, GRAVITY, 0)
  self.velocity = self.velocity + gravity

  local obj_world_pos = go.get_position() + self.velocity * dt

  go.set_position(obj_world_pos)
end
3 Likes

If you don’t have a large amount of objects that would work fine. You can even do simple collision detection and separation—it’s explained in the physics manual here: http://www.defold.com/manuals/physics/.

2 Likes

That’s a great idea! Thanks! With a little math, I could even compensate for world gravity, so I could actually simulate multiple simultaneous gravities this way.

3 Likes