Friday, May 21, 2010

Shadows in Raphaël.js

‹prev | My Chain | next›

Last night I made a bit of a mess out of animating my players and labels as they move about the room in my (fab) game. It works:



But it is done by independently animating the label and the player. The label is offset by 10 pixels, but everything else about the label is duplicated in the Player. I have to stop both the Player and the label the same way, I have to animate both the same way, and I have to initially draw both the same way. That's a lot of duplication.

So let's try it another way. Instead of animating the label as an independent object, I will hook it into the Player animation via raphaël.js's onAnimation callback:
Player.prototype.attach_drawable = function(drawable) {
this.drawable = drawable;
var label = drawable.paper.text(this.x, this.y + 10, this.id);
this.label = label;

drawable.onAnimation(function(){
label.attr({x: drawable.attr("cx"), y: drawable.attr("cy") + 10});
});

};
I can then eliminate all other references to label in the code because this callback will draw the label in a new position each increment of the Player (or the drawable representation of it) along its path about the room.

Nice!

The only difficulty I had was choosing the "right" X and Y. I know from playing about with raphaël.js over the past week that cx and cy are the center of my player avatar in the room, so it only make sense to use them when moving calculating where to put the label.

What I could not figure out was how to set the location of the label. I initially tried cx and cy for that as well, but it had no effect. The label stayed in the start position as the Player moved about the room. I had expected x/y to start the label at that position and then draw the label to the right of center, but, in the end, it does exactly what I had hoped for:



Up next: more fab.js as I get chatting underway.

Day #110

2 comments:

  1. nice! ok so i don't have the stylesheet(s) so don't laugh to hard at this question, and considering you aren't worried about it, you might not care. but about the positioning....are they absolutely positioned?

    ReplyDelete
  2. Nope. They are positioned on an SVG "paper" by raphaël.js. Among the many nice things about using raphaël.js is that I do not have to care about absolute vs. relative positioning / checking if players are out of bounds or even the coordinates withing the room. Raphaël.js takes care of all of it!

    Even when I was doing this by hand with a canvas tag, I could largely ignore CSS positioning concerns. Very liberating :)

    FWIW this is the entire stylesheet that I am using: http://github.com/eee-c/my_fab_game/blob/raphael.js/stylesheets/board.css

    ReplyDelete