Triggering events when in proximity

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:"beginContact",function(evt){


}, this);

Can you give some more pointers. This is my project:,41805169

So, a good starting point:

  1. Add a p2 box shape body for your trigger area
  2. Check the Sensor attribute to be true
  3. 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.

1 Like

I am getting an error:
this.entity.script.p2World is undefined

Is this.entity the same entity that has the script p2World?

1 Like

No. I added p2World to root:

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.

1 Like

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.

1 Like

Can you tell me how to define it here with the help of a code?"beginContact",function(evt){"beginContact", evt.bodyB.entity);"beginContact", evt.bodyA.entity);
}, this);

Something like this.

1 Like

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:


Wow, you guys are best. I see my mistake. Thanks a bunch.