Skip to content

Category and Mask Bits

selimanac edited this page Oct 8, 2024 · 3 revisions

Category and mask bits for collision filtering function similarly to Group and Mask in Defold, operating only within a single group.

Each category should be a unique power of two, ensuring clear and non-overlapping bitwise representations. For more information on bitwise operations, refer to the Defold API docs.

While categories are limited to 64 bits, it is strongly recommended to stay within 32 bits due to potential platform differences.

Example

Collision Bits:

You can use tables to define your bits.

local collision_bits = {
	PLAYER      = 1,	-- (2^0)
	ENEMY       = 2,	-- (2^1)
	GROUND      = 4,	-- (2^2)
	ITEM        = 8,	-- (2^3) 
	WALL		= 16,	-- (2^4) 
	ALL         = bit.bnot(0)  -- -1 for all results
}

Category Bit:

Each AABB can belong to a single category bit. The category bit is optional; if left blank, it will belong to ALL categories.

local group_id = daabbcc.insert_aabb(group_id, x, y, width, height, collision_bits.PLAYER)

local group_id = daabbcc.insert_gameobject(group_id, go_url, width, height, collision_bits.ENEMY)

Mask for Queries & Raycast:

You can use the bit.bor() bitwise operator to combine multiple masks in the query or raycast results. The mask bits are optional; if left blank, it will not mask.

-- Mask bits to use with queries or raycast
local mask_bits = bit.bor(collision_bits.ENEMY, collision_bits.ITEM)

local result, count =  daabbcc.query_aabb(group_id, x, y, width, height, mask_bits)
local result, count =  daabbcc.query_id_sort(group_id, aabb_id, mask_bits)
local result, count =  daabbcc.raycast_sort(group_id, start_x, start_y, end_x, end_y, mask_bits)