Externally calling collision method

Externally calling collision method
0

Is there a way to call a collision detection method on a node from outside of the node’s script? Example:

let collisionNode = cc.find('/Canvas/CollisionNode')

collisionNode.onBeginContact((contact, selfCollider, otherCollider)=>{
  // Collision code in here
});

Is something like this allowed or do I always need to detect collision from inside a script attached to the node itself?

it is allowed, but i don’t think it’s recommended. how do you know to provide the correct contact/selfCollider/otherCollider? because these parameters make sense in architecture of box2d and how it handles collisions (contacts) internally, i don’t think parameters, especially the “contact” one, makes sense outside this system.

from the docs on PhysicsCollider,

PhysicsContact will be generated during begin and end collision as a parameter of the collision callback.

however, if the “collision code” is generic, perhaps you could extract it to a separate method, in a library of sort/base class.

what exactly are you trying to achieve?

detection of the collision should happen on the script itself, however you can setup a event emitter to send a message to all listeners when that collision happens, that’s the standard way you want to deal with cross script communications, send messages to listeners

you could also setup a property on your other script that expecting the type of collisionnode and then use the UI to drag your collision node into your other script

Thanks @Karg and @skara. I think events might be the best solution for me. I wasn’t trying to achieve anything too special, just trying to avoid script bloat by having too many scripts :sweat_smile: