Box2D Question (group limit related)

Hey, I’m looking in the Box2D documentation and I’m seeing that there’s support for passing user data along with the b2Fixture, b2Body, and b2Joint objects: https://box2d.org/documentation/md__d_1__git_hub_box2d_docs_loose_ends.html#autotoc_md120

I’m wondering, would it be possible to implement some way to use this in our projects? For instance, if we could store the factory information which created the instance inside the userdata, then if a collision happens we could check to see which factory created the object as a means of handling the collision logic. Or is there some better way I’m not seeing? Maybe the group limit won’t be a concern but as a developer it does concern me to design all my logic knowing that I have such a small amount of possible groups available.

As you can imagine, we are already using this user data internally to associate the box2d object with the game object.

You can build this Lua table yourself by using the url to the collision object.

As Mathias suggests I’d build this on top of the engine in Lua. Here’s a utility module for creating and deleting game objects while keeping track of some additional data about the objects (Untested code!):

-- spawner.lua

local M = {}

local objects = {}

function M.create(factory_url, url, position, rotation, properties, scale)
	local id = factory.create(factory_url, url, position, rotation, properties, scale)
	local object = {
		id = id,
		factory_url = factory_url,
		data = properties
	}
	objects[id] = object
	return id
end


function M.delete(id)
	go.delete(id)
	objects[id] = null
end

function M.factory(id)
	local object = objects[id]
	return object and object.factory_url
end

return M


-- some.script

local spawner = require "spawner"

function init(self)
	-- create game objects using a factory like you'd use factory.create()
	spawner.create("#orcfactory", url, position, rotation, properties, scale)
end

function on_message(self, message_id, message, sender)
	if message_id == hash("collision_response") then
		if message.other_group == hash("enemy") then
			if spawner.factory(message.other_id) == "#orcfactory" then
				print("Collided with an enemy from the orc factory")
				spawner.delete(message.other_id)
			end
		end
	end
end
4 Likes

Ah cool, thank you. I’ll have to compare the performance of this approach vs the more generic gop table lua helper I’m using. This seems like it would perform better though so I’ll definitely give it a shot :slight_smile: