matter-js
matter-js copied to clipboard
Implement z-index for renderers
Taking your Newton's Cradle example as a starting point (http://brm.io/matter-js/demo/#newtonsCradle) is it possible to have the constraint lines sit behind the circles? I couldn't see anywhere to set a z or z-index value (or equivalent). I also tried swapping the order that the circle and constraint get added to the composite but that didn't seem to have any affect either.
Thanks
The debug renderer doesn't currently support zIndex
I'm afraid. I'd accept a pull request though. You'd need to add body.render.zIndex
, and inside Matter.Render
create a buffer and add all constraints and bodies, then sort by it. It should probably be an opt-in option though as it would be reasonably intensive (unless you do some special optimisations), it would also break some of the optimisations for wireframe mode (which need to continue working).
@liabru Can you give a simple sample or the key code that can change sprite of zIndex dynamic.Thanks.
Had this specific need for an app, ended up adding:
allBodies.sort((a, b) => {
const zIndexA = a.render && typeof a.render.zIndex !== 'undefined' ? a.render.zIndex : 0;
const zIndexB = b.render && typeof b.render.zIndex !== 'undefined' ? b.render.zIndex : 0;
return zIndexA - zIndexB;
});
at the top of Render.world
.
Regarding performance, it seems quite minimal, profiling ~300 bodies, i get a ~0.10ms hit on the Render.world()
call.
Is there a way to use this trick without having to build matter.js ? And if not, is there somenone so nice to share his own build with me ? Thanks !
I also would like to have this feature. Meanwhile, here is a trick based on the following observations. :
- It seems that the render first displays bodies before composites.
- Within each "family" (body, composite) : the order of display is the order of addition to the world. So, if I want to display a body B in front a composite C, I make a new composite with B, and add it to world AFTER adding C.
In my solution for this I went with the following:
In this example I'm using "category" to sort items. With items with a lower category "in front"
This only does the "math" for ordering when adding items to the canvas, since my items will not be changing zIndex. But naturally if you know you changed items you can do an abitary sort on demand.
Matter.Events.on(engine.world, "afterAdd", function(items) {
engine.world.bodies.sort((a, b) => {
return b.collisionFilter.category - a.collisionFilter.category;
});
});
Just wanted to share what I did.