问题
In the famo.us source I see that two things are emitted upon collision: the 'collision' string, and a variable called collisionData, like this: (physics/constraints/Collision.js, lines 112-122):
if (this._eventOutput) {
var collisionData = {
target : target,
source : source,
overlap : overlap,
normal : n
};
this._eventOutput.emit('preCollision', collisionData);
this._eventOutput.emit('collision', collisionData);
}
I know how to use the 'collision' string like so:
collision.on('collision', function() {
// do stuff
};
But, it would be very helpful to know target and source for a collision event. How do I get access to collisionData? collision.collisionData returns 'undefined'.
回答1:
Get the object from the return event object:
collision.on('collision', function(data) {
// do stuff
console.log('data', data);
console.log('target', data.target);
console.log('source', data.source);
});
The target
and source
returned are the particles of the body objects you attached to create collision.
Example Code here (not tested fully)
Just do something like the following to track a unique id of who bumped together.
// assuming your body is called body and body1 respectively
// also, this is just partial code.
var uniqueID = 0;
body.particle = new Circle({
radius: 50,
position: [x, y, 0]
});
body1.particle = new Circle({
radius: 50,
position: [x, y, 0]
});
body.particle.uniqueID = 'body' + uniqueID;
uniqueID += 1;
body1.particle.uniqueID = 'body' + uniqueID;
collision.on('collision', function(data) {
// do stuff
console.log('target id', data.target.uniqueID);
console.log('source id', data.source.uniqueID);
});
来源:https://stackoverflow.com/questions/27714976/famo-us-access-to-collisiondata-upon-collision-event