javascript - Box2dWeb call function when objects collide -
i'm new javascript , box2d, wondering if knows how can call custom function when 2 objects collide. tried using examples uses b2contactlistener
without succes. i've placed object above , let standard box2d physics it's thing.
i recieve 2 console outputs, first null
, second ball
following code:
var listener = new box2d.dynamics.b2contactlistener; listener.begincontact = function(contact) { console.log(contact.getfixturea().getbody().getuserdata()); console.log(contact.getfixtureb().getbody().getuserdata()); };.
the 2 objects need collide b2_dynamicbody
(ball) , b2polygonshape
. (rectangle). using bodydef.userdata = "ball";
in ball.js , bodydef.userdata = "mouse";
in mouse.js try identify if hit. instead ball displayed.
next i'm sure not correct way detecting collision :p hope i've explained enough, steer me in right direction?
ok solved myself, apparently had add custom event world create box2d. so, issue solved me reading big chunks of box2d documentation/manual can found here:
i started adding string userdata()
every object can collide , has else next colliding. using following code:
bodydef.userdata = "car";
note: every object has have it's own unique string.
then created new contact listener (formulated in question above) , listened fixtures colliding each other. when happens, 'save' fixtures userdata()
in variables can use objects collide each other.
var contactlistener = new box2d.dynamics.b2contactlistener; contactlistener.begincontact = function(contact) { var fixa = contact.getfixturea().getbody().getuserdata(); var fixb = contact.getfixtureb().getbody().getuserdata(); // if else statement here... }; world.setcontactlistener(contactlistener);
finally, added last statement world.setcontactlistener(contactlistener);
add event world, making possible listen collisions, forgot add , problem.
hope finds usefull!
Comments
Post a Comment