In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions between ball pairs.
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 serves as a method within each Ball object
Ball.prototype.event_handler = function(shape, ID) {
console.log("ball " + this.ID + " caught message from ball " + ID);
};
With the hope that occasionally one ball will intercept a message from another, unfortunately, such occurrences are never observed.
The desire is to structure things in a manner allowing the event handler to:
- pass on the event when
this.ID == ID
- halt event propagation if
this.ID != ID