How can i trigger events when two objects are near each other. My world uses p2.js instead of normal physics. Any help with it??
Hi @mortal_phoenix,
On p2.js shape scripts there is a Sensor property, checking that means this body will not produce contacts (you aren’t going to bounce/hit on this collision shape) but will only report collisions on an event listener.
So you can use a dummy p2 shape for that to find out when another body enters that trigger area.
Now on the p2World script instance you can do something like this to listen for those contacts:
this.entity.script.p2World.world.on("beginContact",function(evt){
console.log(evt.bodyA.entity.name, evt.bodyB.entity.name);
}, this);
Can you give some more pointers. This is my project:
https://playcanvas.com/editor/code/755718?tabs=42066585,41805169
So, a good starting point:
- Add a p2 box shape body for your trigger area
- Check the Sensor attribute to be true
- Add the code I’ve posted above on a script attached to the entity that holds the p2 world script.
If you do all this, you will start getting console messages in your browser dev tools when p2 bodies enter the trigger area.
I am getting an error:
this.entity.script.p2World is undefined
Is this.entity
the same entity that has the script p2World
?
That’s why it’s undefined. The code you have is not on the same entity therefore script.p2World
doesn’t exist.
More the code to be on the same entity that has has p2World scriptype attached.
I am trying to add it to a small model. If i assign p2World to it, the level just falls apart, i mean disorients. Do i have to add p2Box instead of p2World?
The world needs to be on one entity only, IE root
Boxes for objects in the world.
That beginContact event that Leonidas has posted is a global event fired from the world object.
It’s up to you to take that global event and handle it. Eg you could fire a contact even on both entities that has collided.
Can you tell me how to define it here with the help of a code?
this.entity.script.p2World.world.on("beginContact",function(evt){
evt.bodyA.entity.fire("beginContact", evt.bodyB.entity);
evt.bodyB.entity.fire("beginContact", evt.bodyA.entity);
}, this);
Something like this.
I really hate to trouble you guys, but it is giving same error “this.entity.script.p2World is undefined” .
I tried to add it to police entity same error . I added it to world, still i get the same error. Where do i define it ?? I want it so that when car touches the police box , an event triggers.I have added sensor to police.
Here’s an example of what me and Leonidas were asking you to do: https://playcanvas.com/editor/scene/1085268
Wow, you guys are best. I see my mistake. Thanks a bunch.