Thursday, June 24, 2010

Sending Artificial Event to Raphael.js Nodes

‹prev | My Chain | next›

Last night, I figured out how to generate coordinate based click events with document.createEvent, event.initMouseEvent, and element.dispatchEvent. It was an interesting experiment, but of no practical use unless I can use it to generate location based events in my (fab) game.

Yesterday, I was able to generate click events to move players about in my (fab) game. Today, I would like to decorate those same events so that players will not follow them (but may respond to collisions).

So I walk through the same document.createEvent / event.initMouseEvent / element.dispatchEvent code, this time adding a boolean attribute to the event:
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 1, 0, 0, 50, 450, false, false, false, 0, null);
evt.is_collision = true
room.paper.canvas.dispatchEvent(evt);
That still works (the player moves to 50,450), so let's try ignoring it in the game:
Player.prototype.notify = function(evt) {
if (!evt.is_collision) return null;
switch(evt.type) {
// send events to players
}
};
Running through the same steps with the decorated event, my player now stays put. Nice!

Now, let's see if I can send that event to the player. When I first attach the raphaël.js avatar to the player, I add a click handler to bounce the player:
Player.prototype.attach_avatar = function(avatar) {
var self = this;

avatar.click(function(evt) {
console.debug("here!");
if (evt.is_collision) self.bounce_away();
});


// more initialization
}
Sadly, when I send the event to the room:
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 1, 0, 0, 50, 450, false, false, false, 0, null);
evt.is_collision = true
room.paper.canvas.dispatchEvent(evt);
Nothing happens.

Eventually, I figure out that I can get this working if I send the event directly to the player:
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 1, 0, 0, 50, 450, false, false, false, 0, null);
evt.is_collision = true
p.avatar.node.dispatchEvent(evt);
Hrm. I'm not quite sure that will work for me. I had hoped the event would bubble up from the room, but it seems the players are lower in the bubbling sense. I will have to ruminate on this.


Day #144

No comments:

Post a Comment