Search code examples
collision-detectionfabricjs

intersectsWithObject() doesn't seem to work with objects in groups


I have a Fabric.js canvas with a group of shapes on it (a "token") and a rectangle that I'm going to drag the token onto (a "platform"). Dragging the token onto the platform will make various things happen.

When I call token.intersectsWithObject(platform), everything works great. But I'm going to have several platforms to drag tokens onto, and I want to improve the precision of the drag-and-drop interaction, so I've decided that when checking for collision, I only want to consider the base of the token, not the whole thing.

This shouldn't be too difficult, since the base of the token is a shape. All I have to do is store a reference to that shape in token.base and call token.base.intersectsWithObject(platform).

But for some reason, that doesn't work. token.base.intersectsWithObject() exists, but it always returns false. I can't figure out why. Can anyone help? Here's a CodePen; flip the switch at the top of the JavaScript to toggle the relevant logic between token and token.base.


Solution

  • The object base is in the group. Its coordinates are not changing because it is in the group. If you do some console logging, you will see that the coordinates of the group does change while the coordinates of the object within the group does not change. So in theory the base object is not intersecting with the platform

    console.log('Left margin of group =', fred.getLeft());
    console.log('Top margin of group =', fred.getTop());
    console.log('Left margin of base =', fred.base.getLeft());
    console.log('Top margin of base =', fred.base.getTop());
    

    CodePen