I want to write a simple JavaScript animation that makes some balls move inside a canvas. I want to detect collisions with custom events handled with Backbone.js instead of having a nested for loop that checks for collisions between each pair of balls.
var j;
for (j = 0; j < N_BALLS; j++) {
ball_center = new Point(..., ...);
ball_shape = new Circle(ball_center, ball_radius);
ball_velocity = ...;
ball_ID = j;
balls[j] = new Ball(ball_shape, ball_velocity, ball_ID);
_.extend(balls[j], Backbone.Events);
balls[j].on("imhere", balls[j].event_handler);
}
function animate() {
if (!paused) {
context.clearRect(0, 0, canvas.width, canvas.height);
var j;
for (j = 0; j < N_BALLS; j++){
balls[j].updatePosition();
balls[j].trigger("imhere", balls[j].shape, balls[j].ID);
}
for (j = 0; j < N_BALLS; j++)
balls[j].draw(context, '#0000ff');
window.requestNextAnimationFrame(animate);
}
}
The event_handler is a member method of each Ball object
Ball.prototype.event_handler = function(shape, ID) {
console.log("ball " + this.ID + " caught message from ball " + ID);
};
I would expect that sometimes a ball catches one message from another one, but this is NEVER the case.
I would like to arrange things in such a way where the event handler can:
- forward the event when
this.ID == ID
- stop event propagation if
this.ID != ID