phaserjs / phaser

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
https://phaser.io
MIT License
37.19k stars 7.1k forks source link

Collision filter with mouse for matter physics #3699

Closed rimonmath closed 6 years ago

rimonmath commented 6 years ago

I found two methods body.setCollisionCategory(cat1); body.setCollidesWith([cat1, cat2]); Using these two methods I can easily filter collision between two bodies. But I didn't find any example or documentation about how to do collision filter with mouse. I want that some bodies can be dragged with mouse and some bodies can't. Can you give an example?

hexus commented 6 years ago

Check out this example:

http://labs.phaser.io/edit.html?src=src\physics\matterjs\drag%20with%20pointer.js

As for limiting which bodies a mouse spring can affect, I know you can access the constraint object as such:

var mouseSpring = this.matter.add.mouseSpring();
console.log(mouseSpring);

But there don't seem to be any handy methods for setting the collision filter.

The raw collision filter of the constraint is available here, however:

console.log(mouseSpring.constraint.collisionFilter);
// {category: 1, mask: 4294967295, group: 0}

I think it would be good for us to implement the setCollisionCategory() and setCollidesWith() methods for the PointerConstraint class.

rimonmath commented 6 years ago

This example contains only one body which is draggable. Can you add another body which is not draggable?

photonstorm commented 6 years ago

The easiest way is to just set a collision group in the constraint options:

http://labs.phaser.io/view.html?src=src\physics\matterjs\drag%20filter%20with%20pointer.js

Not sure this needs new constraint methods as you can pass it in easily enough (and for a constraint it's unlikely to change beyond creation either)

If you're going to use matter then it's well worth spending some time learning about how it handles collision groups and filters internally, which you can find in the matter.js docs.

hexus commented 6 years ago

Ah, brilliant! I didn't realise that was possible. :)

@rimonmath:

this.matter.add.mouseSpring({ length: 1, stiffness: 0.6, collisionFilter: { group: canDrag } });

https://github.com/photonstorm/phaser3-examples/blob/73bc72df0a0aba50589e199400ba404cb47987c5/public/src/physics/matterjs/drag%20filter%20with%20pointer.js#L28-L46

rimonmath commented 6 years ago

@hexus Thank you very much, this example really helped me a lot :)

hexus commented 6 years ago

No worries - @photonstorm made it for you! :)