Wednesday, June 16, 2010

Collision Broadcast with Fab.js

‹prev | My Chain | next›

Man, collisions are hard. I have spent the better part of a week getting them in place, working in the right direction, and working properly when first entering the room. I am not even attempting to do this on the backend (where it probably ought to take place). And yet I am still not done.

Up tonight, I need to get collisions to broadcast. Right now, my player bounces on collisions, but other players do not see the collisions:



Currently I have a bounce_away client-side method governing this behavior:
Player.prototype.bounce_away = function() {
this.mid_bounce = true;
var x = this.x - 2*Player.radius*this.direction.x,
y = this.y - 2*Player.radius*this.direction.y;

var self = this;
this.avatar.animate({cx: x, cy: y}, 500, "bounce",
function(){self.mid_bounce = false;});
setTimeout(function(){ self.mid_bounce = false; }, 1000);

this.x = x;
this.y = y;
};
I am going to need to broadcast a "bounce to", so first up, I factor out the destination bounce into its own method:
Player.prototype.bounce_away = function() {
var x = this.x - 2*Player.radius*this.direction.x,
y = this.y - 2*Player.radius*this.direction.y;

this.bounce_to(x, y);
};

Player.prototype.bounce_to = function(x, y) {
this.mid_bounce = true;

var self = this;
this.avatar.animate({cx: x, cy: y}, 500, "bounce",
function(){self.mid_bounce = false;});
setTimeout(function(){ self.mid_bounce = false; }, 1000);

this.x = x;
this.y = y;
};
With that, I can tap into the notification system that I already have in place to communicate to the fab.js backend:
Player.prototype.bounce_away = function() {
var x = this.x - 2*Player.radius*this.direction.x,
y = this.y - 2*Player.radius*this.direction.y;

this.notify_server('bounce', {id: this.id, x: x, y: y});
this.bounce_to(x, y);
};
I need a (fab) app that will respond to that bounce. I copy & paste the skeleton from the "player walk" resource and wind up with this:
  ( /bounce/ )
( function() {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) {
broadcast(comet_bounce_player(obj.body));
update_player_status(JSON.parse(""+obj.body));
}
return listener;
};
} )
(the copy & paste is duly noted with a TODO to DRY up the code)

The broadcast of the bounce player interfaces with the PlayerList in all attached clients to tell the player to bounce. That method needs to look up the player and tell it to bounce using the newly minted bounce_to method:
PlayerList.prototype.bounce_player = function(attrs) {
var player = this.get_player(attrs.id);
if (player) {
player.stop();
player.bounce_to(attrs.x, attrs.y);
}
};
And, just like that, I have bouncy collisions in both my window and all other windows:



Nice. That was almost too easy. I do believe that I will pick up tomorrow trying to find what new bug I have introduced.

Day #136

No comments:

Post a Comment