Sunday, June 6, 2010

Overflow Events in Raphaël.js

‹prev | My Chain | next›

Way back when I was first experimenting with raphaël.js, I ran into a problem with capturing events on the room itself (the paper in Raphaël terms). My eventual solution was to listen on the paper's container. My son quickly discovered during our tag games in my (fab) game that players can hide in the container.

His cheating ends today!

The event code is decorated before notifying subscribers. That seems a good place to start:
Room.prototype.decorate_event = function(evt) {
return {
type: evt.type,
x: evt.pageX - $(this.container).offset().left,
y: evt.pageY - $(this.container).offset().top
};
};
That seems easy enough. I simply need to check if the player is trying to sneak out of bounds—either by moving less than zero or greater than the paper's width. Less than zero is easy and I ought to be able to grab the width of the paper from its attrs property:
Room.prototype.decorate_event = function(evt) {
var x = evt.pageX - $(this.container).offset().left;

if (x < 0)
x = 0;
else if (x > this.paper.attrs.width)
x = this.paper.attrs.width;

var y = evt.pageY - $(this.container).offset().top;
if (y < 0)
y = 0;
else if (y > this.paper.attrs.width)
y = this.paper.attrs.width;


return {
type: evt.type,
x: x,
y: y
};
};
Unfortunately, there doesn't seem to be an attrs property on the paper like other raphaël objects. So I have to settle for using the API which give access to the dimensions directly via width and height properties:
Room.prototype.decorate_event = function(evt) {
var x = evt.pageX - $(this.container).offset().left;

if (x < 0)
x = 0;
else if (x > this.paper.width)
x = this.paper.width;

var y = evt.pageY - $(this.container).offset().top;
if (y < 0)
y = 0;
else if (y > this.paper.width)
y = this.paper.width;

return {
type: evt.type,
x: x,
y: y
};
};
With that, the decorated event that is sent to subscribers (like the player) are limited to be within the bounding box. That's enough for today—it was a quite day :)

Up tomorrow: first I'm gonna thrash my son in tag. After that, I'll be poking around the fab.js / comet connection. I have introduced a bug somewhere that needs sorting out.

Day #126

No comments:

Post a Comment