Showing posts with label raphaeljs. Show all posts
Showing posts with label raphaeljs. Show all posts

Sunday, October 3, 2010

Readying Things for the Kids

‹prev | My Chain | next›

Up tonight, I need to start thinking about making things a bit easier for my kids to code my (fab) game.

I expect the entry point that will pull in the kids will be the frames animation that prompted me to write the animate-frames plugin for raphaël.js. The problem right now is that the responsibility for describing the frames is in the game room:
Room.prototype.player_frames = function() {
var standing = [
{ label: "left_leg",
style: "fill:none;stroke:#000000;stroke-width:0.99999779px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;display:inline",
d: "M 9.7001312,18.93142 C 9.4644309,22.702657 9.2287306,26.473893 8.9930303,30.24513" },

// ...
];

var walking = [
// ...
];

return [standing, walking];
};

Room.prototype.draw_player = function(player, color) {
var frames = this.player_frames();

// set x-y position from player.x, player.y
return this
.paper
.svg_frames(frames)
.translate(player.x, player.y);
};
It is not completely crazy that the room draws the player. The game board is responsible for holding the reference to the raphaël paper object that draws things. It also needs to keep track of players, makes sure that they do not stray out of the room and sends mouse events to the players.

OK, so that is pretty much a bunch of bull. The room might need to ask the player how the player ought to be drawn, but it has no business holding onto that information.

So first up, I make a player_frames global object, in a separate file, javascript/player_frames.js, that will hold that information. The kids ought to be able to get in there and play with things without being distracted by all the other code. As an intermediate step, I replace the player_frames() call with a reference to the global object:
Room.prototype.draw_player = function(player, color) {
// set x-y position from player.x, player.y
return this
.paper
.svg_frames(player_frames)
.translate(player.x, player.y);
};
I then need to pull that global into the page, which is done as a fab.js HTML app:
// ...
( SCRIPT, { src: "/javascript/room.js",
type: "application/javascript" } )()

( SCRIPT, { src: "/javascript/player_frames.js",
type: "application/javascript" } )()


( SCRIPT, { type: "application/javascript" } )
( board_js_string )
()
// ...
Reloading, I start getting all sorts of undefined errors. It takes me a bit, but I eventually realize that one of the problems with HTML (fab) apps is that the server needs to be restarted when changes are made—even to HTML pages.

Once I figure that out, I get things working. Ultimately, I make the Player responsible for the player frames:
Room.prototype.draw_player = function(player, color) {
// set x-y position from player.x, player.y
return this
.paper
.svg_frames(player.frames())
.translate(player.x, player.y);
};
Ah, much better.

That will suffice for tonight. Up tomorrow, I need to get some of the changes to the animate-frames plugin back into the main repository. I would also like to make sure that everything still works with the latest version of fab.js.

Never a shortage of things to learn.


Day #245

Saturday, October 2, 2010

Preventing Unnecessary Loss of Limbs in Games

‹prev | My Chain | next›

The players in my (fab) game are suffering some serious injuries:



Loss of limbs is not occurring immediately or even after a long time roaming about the game room. No, the player's legs are becoming detached after bouncing into each other repeatedly:



Crazy. Where does one even start to track down a problem like that?

Well, since I have made changes to it recently and since it is controlling the player walking animation, I start with animate-frames, my animation plugin for raphaël.js.

In there, I add an offsets() method to the individual frames making up the animation. The offsets calculate the x-y differences between the various strokes of the pen that comprise the frame (e.g. a pen stroke for a foot, leg, body, etc). The x-y differences are between each of the elements and the last element.
  Frame.prototype.offsets = function() {
var diffs = []
,main = this.getBBox();

for (var i=0; i<this.elements.length-1; i++) {
var box = this.elements[i].getBBox();
diffs.push([main.x - box.x, main.y - box.y]);
}

return diffs;
};
The individual offsets should always remain the same—a player's foot should stay 16 pixels away from the body if it was first drawn 16 pixels away. Looking at the first offset when the player first enters the room, I find:
[
0: -6.787272029958575
1: -16.76693459682566
]
After moving the player about the room for a bit, I find:
[
0: -6.787412453957089
1: -16.766913780265497
]
Almost exactly the same. I am not sure about the differences (in the 10,000ths decimal place). Is that caused by simple rounding errors? Maybe timing differences between stop() calls of individual elements is sufficient to cause that problem? Is that small a change even a problem?

Before investigating further, I try colliding my player with another player in the room. Then, I check the offsets again:
[
0: -6.039369453957079
1: -16.56494217026568
]
That is a much more dramatic change. Banging players together some more furthers the offset change:
[
0: -5.144486633957058
1: -16.511516330265806
]
Whatever the problem, it seems that the bouncing of players is the best place to continue my investigation.

But wait...

If I know the expected offset of the individual elements in a frame, can I use them to sync the frame back up to where it is supposed to be?

I think that I can run through each offset, calculate the difference between the current and original offset, then translate the affected frame element by the tiny offset it needs to get back to the right place:
  Frame.prototype.tighten = function() {
var offsets = this.offsets();
for (var i=0; i<offsets.length; i++) {
var x_diff = offsets[i][0] - this.original_offsets[i][0]
,y_diff = offsets[i][1] - this.original_offsets[i][1];

this.elements[i].translate(x_diff, y_diff);
}
};
Yay! That works just as expected. A player falling to pieces gets put back together (tightened up) with a single call.

To put that to practical use, I call it at the end of the translate() method of each Frame object. And, just like that, my players keep all of their limbs.

That is not an entirely satisfactory solution—I never did solve why limbs were flying away in the first place. Rounding errors seems a reasonable explanation, but reasonable explanations do not elicit learning the way that digging deep does. Something to investigate another day.


Day #244

Friday, October 1, 2010

Gah! I Still Don't Know Closures

‹prev | My Chain | next›

I ended a big refactoring of animate-frames last night with some less than DRY code:
  Frame.prototype.remove = function () {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].remove();
};
};

Frame.prototype.show = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].show();
};
};

Frame.prototype.hide = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].hide();
};
};

Frame.prototype.stop = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].stop();
};
};
Let's see if I can DRY that up a bit.

For each of those methods (remove(), show(), hide(), and stop()), I set the prototype property of the Frame object to that repetitive function:
  var methods = ['remove', 'show', 'hide', 'stop'];
for (var i=0; i<methods.length; i++) {
var method = methods[i];
Frame.prototype[methods[i]] = function () {
console.log(method);
for (var j=0; j<this.elements.length; j++) {
this.elements[j][method]();
};
};

}
The only funky thing in there is accessing the method property on each element. element.stop is the same thing as element['stop']—both of them are functions that stop raphaël.js elements. Putting parentheses on either invokes the function: element.stop() and element['stop']().

At least I think that will work. Sadly, when I load that up in my (fab) game, the players do not move at all. Checking the output in the Javascript console, I see that the method being called is always stop()—even when the show() and hide() methods are being invoked.

What gives? Am I messing things up with the property method call?

Actually, no. I have messed up, but what I have messed up here is my Javascript closures. The anonymous function that is being assigned to the Frame.prototype method is itself a closure:
  var methods = ['remove', 'show', 'hide', 'stop'];
for (var i=0; i<methods.length; i++) {
var method = methods[i];
Frame.prototype[methods[i]] = function () {
console.log(method);
for (var j=0; j<this.elements.length; j++) {
this.elements[j][method]();
};
};

}
But the context that it is enclosing includes that var method. My mistake is that the context, the value of var method changes with each iteration through the list of methods. At the end of the iteration, the method variable is set to 'stop'.

What this means is that every one of the methods that I just defined is a stop() method. I do define Frame.prototype.remove(), Frame.prototype.show(), etc. But, when each is called, they use the method from the enclosed context—which is forever more set to "stop".

So what can I do to get the context to stick? I need to add more context—another function:
  var methods = ['remove', 'show', 'hide', 'stop'];
for (var i=0; i<methods.length; i++) {
Frame.prototype[methods[i]] = function(method) {
return function () {
console.log(method);
for (var j=0; j<this.elements.length; j++) {
this.elements[j][method]();
};
};
}(methods[i]);
}
For each method that I am defining, I set the prototype method to the return value of calling the anonymous function with the method name:
    Frame.prototype[methods[i]] = function(method) {
// ...
}(methods[i]);
Now, when I return the same function as earlier, the method variable is in a new, separate context—one that will be remembered when the methods are called. To state is more plainly—in order to ensure that a value in a Javascript closure is what you think it is, it must be defined inside another, enclosing function.

That was unexpectedly difficult. Still, I learned me some good closure. I think I will stop there and move on to resolving the weird bounce issue in animate-frames tomorrow.


Day #243

Thursday, September 30, 2010

The Great (Lucky) Refactor

‹prev | My Chain | next›

I got a new feature added to animate-frames last night. Getting there made me realize that the code is a bit messy so tonight I refactor!

Animate-frames is a plugin for raphaël.js that iterates through a series of raphaël/SVG frames as the frames move about the paper. I am using this in my (fab) game to draw and animate players as they move about the game room. I am going to refactor in the game before extracting the changes back out into the plugin.

The refactoring is necessary because many of the methods in the plugin look like:
     stop: function() {
var frames = this.list;
for (var i=0; i<frames.length; i++) {
for (var j=0; j<frames[i].length; j++) {
frames[i][j].stop();
}
}
}
The class is responsible for managing the frames and the parts that make up the frames:



(the parts that make up the frames are the players' body, legs, and feet — each is a different SVG path)

I could make that much cleaner if the frames methods were just responsible for knowing about the frames, but made a separate class responsible for dealing with the pieces. In that case, this:
     stop: function() {
var frames = this.list;
for (var i=0; i<frames.length; i++) {
for (var j=0; j<frames[i].length; j++) {
frames[i][j].stop();
}
}
}
...would become this:
    stop: function() {
for (var i=0; i<this.list.length; i++) {
this.list[i].stop();
}
}
Ah, much better. No more worrying about what that j variable was iterating over. No more trying to discern which of those 6 lines are important. Just one clear iteration through each frame in the animation, telling each frame to stop().

The corresponding stop method on my Frame object is then:
  Frame.prototype.stop = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].stop();
};
};
Again, nice and compact. Just one iteration making it very clear what is going—working through each part that makes up the frame and telling it to stop.

I end up working through half a dozen similar methods. All sorts of weird naming becomes easier (translate_object() becomes just translate() on the Frame object). Initialization code gets separated in much easier to read ways. It is great.

And then something amazing happens....

I load it up in the browser and it just works! I have no tests (note to self: future idea for a chain post) that helped me support the refactoring. Git diff reports:
cstrom@whitefall:~/repos/my_fab_game$ gd --stat
javascript/raphael-animate_frames.js | 192 +++++++++++++++++++---------------
1 files changed, 108 insertions(+), 84 deletions(-)
That is a lot of non-trivial change. I had to intentionally break the code to make sure I was running the updated code (I was).

Amazing? Am I that good?

Absolutely not. That was pure luck and I damn well know it. The coding gods should have punished me severely for even attempting it. I give them thanks for going easy on me tonight, but I know I have a doozy of a refactoring fail in my future.

One thing I do notice is that I repeat myself in the simple raphael methods:
  Frame.prototype.remove = function () {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].remove();
};
};

Frame.prototype.show = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].show();
};
};

Frame.prototype.hide = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].hide();
};
};

Frame.prototype.stop = function() {
for (var i=0; i<this.elements.length; i++) {
this.elements[i].stop();
};
};
I also notice that my players become disjointed after colliding too often:



I will pick back up tomorrow with DRYing up my code after the great refactor and trying to solve the detached limb problem.


Day #142

Wednesday, September 29, 2010

Workaround and Hacks

‹prev | My Chain | next›

Tonight, I continue working through a new feature in animate-frames plugin for raphaël.js. This plugin iterates through a series of raphaël/SVG frames as the frames move about the paper. I am using this in my (fab) game to draw and animate players as they move about the game room:



I found last night that it is not possible to animate position changes of elements drawn from the path() method (which my players are). I would like to animate collisions between elements.

My plan tonight is to hide all of the frames, then draw a replacement circle that bounces. At the end of the bounce, I will remove the bounced circle and re-show one of the frames. To accomplish this, I add a third parameter to the animate() method in animate-frames—the same parameter that is in core raphaël describing the easing:
    animate: function(new_attrs, ms, easing) {
}
If that argument is not present, I will fallback to the old behavior (strict translation of coordinates). If that argument is present, then I do as I describe above:
    animate: function(new_attrs, ms, easing) {
if (new_attrs.cx || new_attrs.cy) {
var x = new_attrs.cx || this.getCenter().x
,y = new_attrs.cy || this.getCenter().y;
if (easing) {
this.hide_all_frames();
// replace the frames with a circle at the same location
var c = this.paper.circle(this.getCenter().x,
this.getCenter().y,
20);
var self = this;
c.animate({cx: x, cy: y}, ms, easing, function () {
// when the animation of the circle is done, remove
// the circle, move the frames to the end point and show
// the first frame again
c.remove();
self.translate(x, y);
self.show_frame(self.list[0]);
});

}
else {
this.translate(x, y, ms);
}
}
}
That almost works.

The circle appears, but the frames do not disappear. They stick around and keep moving.

After a bit of a search, I track the problem down to the stop() method in the Player class. Specifically, when a player stops (e.g. when it is about to bounce), the raphael object is not being told to stop:
Player.prototype.stop = function () {
//TODO -- re-enable
// this.avatar.stop();

this.x = this.avatar.getBBox().x;
this.y = this.avatar.getBBox().y;
};
Hunh. That's weird. I wonder why it is disabled....

After re-enabling, I find out why it was disabled—there is no stop() method in animate-frames. So I add one:
    stop: function() {
var frames = this.list;
for (var i=0; i<frames.length; i++) {
for (var j=0; j<frames[i].length; j++) {
frames[i][j].stop()
}
}
I really need to break down and create a Frame class. I iterate over frames and frame elements far too often.

I will leave refactoring for another night. For now, I would be happy just to get things working.

Happily, that was the last change needed:



I could definitely make that animation a little nicer, but, for a proof of concept it will suffice. Tomorrow, I will prettyfy things a bit—both the animation and the code.


Day #241

Tuesday, September 28, 2010

Can't Animate Raphaël path Positions

‹prev | My Chain | next›

I made some good progress last night making animate-frames more raphaël.js-like. Before I push those changes back into the main repository, I would like to explore easing in the animate() method.

Ultimately, the animate() method in animate-frames is calling the translate_object() method, which animates movement with animateAlong():
    translate_object: function(frame, x, y, ms, easing) {
// offset between end coordinates and current location
var x_diff = x - frame[frame.length-1].getBBox().x;
var y_diff = y - frame[frame.length-1].getBBox().y;

for (var i=0; i<frame.length; i++) {
var obj = frame[i];
// calculate path starting from absolute coordinates and moving
// relatively from there by the offset
var p = "M " + obj.getBBox().x + " " + obj.getBBox().y +
" l " + x_diff + " " + y_diff;

// animate along that path
if (ms && ms > 50)
obj.animateAlong(p, ms);
else
obj.translate(x_diff, y_diff);
};
}
My first instinct is to add and easing parameter to animateAlong(). Sadly, according to the documentation (and the code), the method signature only takes path, ms, rotate, and callback (invoked after the animation completes).

Dang.

So maybe I can use animate() instead of animateAlong():
         // animate along that path
if (ms && ms > 50)
obj.animate({x: x + x_diff, y: y + y_diff}, ms, easing);
// ...
But when I do that, my players don't move at all. Grr.. what gives?

To find out, I break the problem down to basics. Using a raphaël paper object, r, I create a circle and animate its center x-coordinate:
c = r.circle(200, 200, 10).attr({stroke: "#333", "stroke-width": 4, "fill": '#333'})
c.animate({cx: 0}, 5000)
That works. The circle moves from 200, 200 to 0, 200 over the course of 5 seconds.

Next I try drawing an object with SVG path information—the same way that the objects inside my animations are being drawn:
o = r.path("m 27.970621,11.503807 c 0.09878,4.794487 -3.625825,9.254299 -8.244694,9.888541 C 15.282994,22.185422 10.583894,19.322284 9.1090954,14.943452 7.4780985,10.605964 9.2934491,5.2861677 13.201573,2.948285 c 3.892493,-2.53638571 9.452051,-1.6375587 12.397375,2.008774 1.523084,1.7954543 2.381825,4.1636216 2.371673,6.546748 z").attr({fill: '#090'})
o.animate({cx: 50}, 5000)
That does not work. The player stays at its original coordinates.

I can animate certain other attributes, such as the fill color:
o.animate({fill: '#00f'}, 5000)
From this, I conclude that it is not possible to animate location elements on objects drawn via paths. That is not too surprising based on my earlier investigation. Not surprising, but still disappointing.

I am not quite ready to abandon easing. I really want to use it to animate collisions (the "bounce" easing is particularly nice). Since I cannot animate-with-easing the SVG paths that make up my frames, I think that I ought to be able to hide the frames, show another object that can be animated. That is not perfect, but it ought to suffice for my purposes.

I will get started on that tomorrow.


Day #240

Monday, September 27, 2010

Better Raphaël Plugins

‹prev | My Chain | next›

Up tonight, I try to get a few more raphaël.js methods into raphael-animate-frames. This plugin for raphael.js cycles through a series of frames, giving the appearance of animating. Additionally, the frames can move together and do other things that normal raphael.js objects can. There are many raphaël things that it cannot do. I am going to start tonight by trying to add an animate() method.

The documentation for animate explains that not all attributes can be animated. I will push that to the extreme and say that only 2 elements can be animated: cx and cy (center x and center y).

Some attributes just do not make sense to be animated. Do the attributes apply to all elements in an animation frame or only some? Actually, reading through the list, I ought to be able to support many eventually, but for now, I just need cx and cy:
Player.prototype.bounce_to = function(x, y) {
this.stop();

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

this.x = x;
this.y = y;
};
I can get a quick and dirty implementation of that by making animate() a simple wrapper around the translate() method:
    animate: function(new_attrs, ms) {
if (new_attrs.cx || new_attrs.cy) {
this.translate(new_attrs.cx || this.getCenter().x,
new_attrs.cy || this.getCenter().y,
ms);
}
}
I will not get easement by using translate(), but it will suffice for tonight.

Up next, I need animate-frames to support a node attribute so that I can get decent collision detection. That turns out to be relatively easy:
    add: function(frame_list) {
for (var i=0; i<frame_list.length; i++) {
this.list.push(this.draw_object(frame_list[i]));
}
this.node = this.list[0][this.list[0].length-1].node;
}
The this.list[0] references the first frame of elements. Using this.list[0].length-1 gives me the last elment drawn in the frame. This seems a reasonable thing—the last thing drawn in a frame is very likely going to be the most prominent feature which makes it ideal to serve at the node attribute.

With that, I can set a boolean on the node indicating that it is the "player" node. If the player node collides with another player node, then collision detection kicks in:
Player.prototype.attach_avatar = function(avatar) {
var self = this;
this.avatar = avatar;

// ...

avatar.node.is_player_circle = true;

// ...

avatar.onAnimation(function(){
// find the colliding element (c_el)

if (!self.initial_walk &&
!self.mid_bounce &&
c_el.is_player_circle &&
c_el != self.avatar.node) {
self._bounce_away(c_x, c_y);
}
});
};
That is a fine stopping point for tonight. I will pick back up with easing tomorrow.


Day #239

Sunday, September 26, 2010

My Dogfood Stinks

‹prev | My Chain | next›


Having resurrected the animate-frames fork of my (fab) game last night, I am ready to play again with my raphaël.js plugin: animate-frames. If I recall correctly, it is very much a work in progress, but is in good enough shape for a demo.

Unfortunately, the my (fab) game code has evolved significantly since last I played with this code. For one thing, the animate-frames plugin does not have a single node on which various attributes can be set:
//... 

// Mark node as player element (for collision detection)
avatar.node.is_player_circle = true;

// ...
For now, I will simply comment out references to node.is_player_circle. I can go back later to get collision detection working well.

Unfortunately, I run into a another problem—the remove() method, used when a player is dropped, is not defined in animate-frames:
Player.prototype.quit = function() {
this.avatar.remove();
this.label.remove();
delete this.x;
delete this.y;
delete this.id;
};
This, I can address relatively easily by adding a method that removes all frames being animated as well as each element in each frame:
    remove: function() {
for (var i=0; i<frames.length; i++) {
for (var j=0; j<frames[i].length; j++) {
frame[j].remove();
};
}
}
This is browser code, so I cannot rely on forEach(). Actually, this is a indication that I ought to be using coffeescript.

At any rate, it works.

Until I hit another problem—collision detection does not work at all. Players simply pass through each other. Eventually, I track this down to the initial_walk attribute on a player. Collision detection does not kick in until the first walk in the room is complete.

The only place that I see initial_walk even mentioned as being set to false is a comment:
Player.prototype.walk_to = function(x, y) {
// ...

// TODO self.initial_walk = false after walk has started

// ...
};
It has been a while since I last fiddled with the animiate-frames stuff, so I am not even going to bother digging through the history of how I got in this state. Instead, I have a peak back in master since I know that collision detection is working in there. Sure enough, it is set:
Player.prototype.walk_to = function(x, y) {
// ...

var self = this;
this.avatar.animateAlong(p, time, function(){
self.initial_walk = false;
});

// ...
};
Grr... that (animateAlong()) is another method that I do not have in animate-frames. I can simulate what I need with setTimeout()—2 seconds after the player first starts walking in the room, wait 2 seconds then mark the initial walk as done:
  var self = this;
setTimeout(function() {self.initial_walk=false;}, 2*1000);
Sadly, that is not the last of my woes. Last up is the lack of support for the animate() method when the players bounce away from a collision:
Player.prototype.bounce_to = function(x, y) {
this.stop();

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

this.x = x;
this.y = y;
};
Blech. I workaround this tonight by using the translate() method, but ick. This has been a tough night eating my own dog food. In order, I wanted the node attribute, the animateAlong() method and the animate() method. I am not sure how realistic the node attribute is, but I really ought to be able get the animateAlong() and animateAlong() methods in there.

Tomorrow.


Day #238

Monday, August 16, 2010

Finishing (hopefully) Touches on Collisions with Faye

‹prev | My Chain | next›

I got collision handling in my (fab) game accommodating faye latency. I did so my making my player larger, slower and detecting collisions at the edge of the player in the direction in which the player is moving.

In the end, the players are a tad large (40 pixels wide in a 500 pixel room) and sluggish (requiring 10 seconds from corner to corner). So first up, I put the player on a diet and move them a little faster:
Player.radius = 15;
Player.shadow_distance = Player.radius + 10;
Player.max_walk = Math.sqrt(500*500 + 500*500);
Player.time_to_max_walk = 8 * 1000;
With that, I need to extend the collision point forward a bit—in essence signal a collision before the collision occurs. That will lead to some phantom strikes, but hopefully nothing too bad. Let's try adding about 10%:
    var c_x = avatar.attr("cx") +
$(self.avatar.paper.canvas).parent().offset().left -
$(document).scrollLeft() +
1.1 * self.direction.x * Player.radius;

var c_y = avatar.attr("cy") +
$(self.avatar.paper.canvas).parent().offset().top -
$(document).scrollTop() +
1.1 * self.direction.y * Player.radius;
That seems to work, except when the player is moving downward in the room. In that case, the extended collision point is overlapping with the player's label. To resolve that, I add an attribute to the player object:
Player.prototype.attach_avatar = function(avatar) {
//...
avatar.node.is_player_circle = true;
//...
}
And use that to ensure that the object that raphaël.js is telling me that is in collision is a player circle:
    if (!self.initial_walk &&
!self.mid_bounce &&
c_el.is_player_circle &&
c_el != self.avatar.node) {
self._bounce_away(c_x, c_y);
}
That actually solves a bit of a problem that I have had in the code for a while—how to test for collisions with "collidable" objects. If there need to be more objects that can collide, then I can test for that attribute. Previously, I had been testing there that the colliding object was not the raphaël paper itself. The new condition handles that case nicely as well (the paper does not have that attribute set).

With that, I still have one minor change that still needs to take place: the bounce away from the collision needs to be a bit further than it had been (the radius of a player). Trial and error suggests that the player radius plus 50% should do:
Player.prototype._bounce_away = function(from_x, from_y) {
this.mid_bounce = true;

var x = from_x - 1.5*Player.radius*this.direction.x,
y = from_y - 1.5*Player.radius*this.direction.y;

this.faye.publish('/players/bounce', {id: this.id, x: x, y: y});
};
That gives me fairly decent collisions, well represented in both my browser and in the browser of other players:



I think I will leave well enough alone at this point. The idle timeout seems to be acting up on me again, so I will look into that a bit more tomorrow before moving onto other things.


Day #197

Sunday, August 15, 2010

Mitigating Faye Latency in Games

‹prev | My Chain | next›

Today, I continue exploring ways to mitigate faye latency as it affects my (fab) game. As noted yesterday, there is a 200 millisecond delay between publishing messages to a faye channel and the message reaching a subscribing function. This has almost no effect in my (fab) game other than collision detection:



The collision is seen much earlier in my player's screen than it is seen on the screens of other players. I have already blindly moved code about in a vain attempt to solve the latency issue. Before moving more code about, a look at the problem I am facing.

As mentioned, there is a 200 millisecond latency in faye communication. Looking at the client-side code, I find some more constraints:
Player.radius = 10;
Player.shadow_distance = 20;
Player.max_walk = Math.sqrt(500*500 + 500*500);
Player.time_to_max_walk = 5 * 1000;
From that, I can determine the speed at which my players can move in the room. The max_walk distance evaluates to 707.1 pixels. If the player takes 5 seconds to make that walk, then the speed is 141.2 pixels/second. Thus, during the 200 millisecond latency, the player will travel 28.2 pixels. That is a little more than the diameter of a player. That pretty much explains the delay that I am seeing.

So how can I mitigate the problem? One thing I can do is slow down the players. If I halve the speed at which players move, then players will travel 14 pixels during the faye latency. That still seems too much since the diameter of a player is 20 pixels. Hrm... well, I could double the size of a player as well:
Player.radius = 20;
Player.shadow_distance = 30;
Player.max_walk = Math.sqrt(500*500 + 500*500);
Player.time_to_max_walk = 10 * 1000;
What will that do?



That is still not good enough. The player is almost completely overlapping the other when the bounce is signaled. It is at this point that I realize part of the problem is that I am detecting a collision at the center of my player. If it were possible to detect a collision at the edge in which the player is moving, things might work better. That is, if the player is moving to the right, then I should try detecting collisions at the center x coordinate plus the radius of the player.

As luck would have it, I am already storing the direction in which a player is moving (so that the bounce away can be in the opposite direction). I can use that to detect edge collisions:
    var c_x = avatar.attr("cx") +
$(self.avatar.paper.canvas).parent().offset().left -
$(document).scrollLeft() +
self.direction.x * Player.radius;

var c_y = avatar.attr("cy") +
$(self.avatar.paper.canvas).parent().offset().top -
$(document).scrollTop() +
self.direction.y * Player.radius;
With that my collisions are actually rather good:



That is a fine stopping for tonight. Tomorrow, I will consider alternatives I have not thought up just yet and hopefully drive toward an all-around satisfying solution. But this is pretty close.


Day #196

Wednesday, July 28, 2010

Always use getBBox() for Raphaël Coordinates

‹prev | My Chain | next›

Up today, I would like to get the onAnimation callback in my (fab) game working with my raphael-animate-frames plugin.

The onAnimation callback is standard raphaël.js that is called after every step of an animation. The animation in my (fab) game does quite a bit. The first thing is move a label (the player's name) along with the player:
  avatar.onAnimation(function(){
console.debug(avatar.attr);
console.debug("x: " + avatar.attr("cx") + ", y: " + avatar.attr("cy"));
self.label.attr({x: avatar.attr("cx"), y: avatar.attr("cy") + Player.shadow_distance});

// more animation code...
}
Unfortunately, that does not work (nor does any of the rest of the animation code). The debug code in there tells me that the x-y coordinates are undefined even though the correct function is being called:
x: undefined, y: undefined
function () {
// delegate to last object in first frame
var obj = this.list[0][this.list[0].length-1];
return obj.attr.apply(obj, arguments);
}
Dang. It would seem that pulling the attr() values off of SVG is not as consistent as I would like. Fortunately, the getBBox() method is available and seems quite a bit more reliable.

If there is one thing that is slowly dawning on me as I do more and more raphaël work, it is that getBBox() is what I need when I want location information. The values that attr() is supposed to have (cx, c, rx, etc) are very much hit-or-miss. I suspect that these are only available if explicitly set when drawing, but that is an investigation for another day. For now, I replace every instance of attr() with a corresponding getBBox() call:
  avatar.onAnimation(function(){
self.label.attr({x: avatar.getBBox().x, y: avatar.getBBox().y + Player.shadow_distance});

// more animation code...
}
One last thing before stopping for the night is that the x-y coordinates from getBBox() are the top-left coordinates. The reason that I had been using cx-cy before was because I wanted the center coordinates for the object.

For that, I add a method, getCenter() to my raphael plugin:
    getCenter: function() {
var bounding_box = this.getBBox();
return {
x: Math.floor(bounding_box.width/2) + bounding_box.x,
y: Math.floor(bounding_box.height/2) + bounding_box.y
};
}
Now I can get more accurate placement in my animations with:
  avatar.onAnimation(function(){
self.label.attr({x: avatar.getCenter().x, y: avatar.getCenter().y + Player.shadow_distance});

// more animation code...
}
I got in trouble adding non-standard methods to my raphaël plugin last night, so I will sleep on the getCenter() method name and implementation before committing it to raphael-svg-frames. Then it will be time to move onto collision detection.


Day #178

Tuesday, July 27, 2010

Careful Naming

‹prev | My Chain | next›


Up today, I would like to add a bit of functionality to my raphael-animate-frames plugin for raphaël.js. I would like to be able to position the frames on the raphaël paper—right now, the frames just show up at the top left of the paper.

In my (fab) game, the frames are being drawn thusly:
  return this
.paper
.svg_frames(frames[0], frames[1])
To position the player, I could expand the svg_frames method to accept x-y coordinates, but that could get messy. I prefer just supplying the frames themselves. But how to move the player?

Raphaël has a translate() method to move objects about the paper. Perhaps I could use that?
  return this
.paper
.svg_frames(frames)
.translate(player.x, player.y);
That'll work. Except it won't. I already have a translate() method in raphael-animate-frames:
    translate: function(x, y, seconds) {
for (var i=0; i<this.list.length; i++) {
this.translate_object(this.list[i], x, y, seconds);
}
this.toggle_frames(seconds);
return this;
}
Aw, dang it. My translate() method has an additional seconds parameter that is not in the core raphaël translate() method. I should have named it differently since it behaves differently.

Ooh. Or I could treat the the seconds parameter as optional. If that parameter is present, then the object moves along a line. If the parameter is not present, then the object moves immediately. That, I can do inside the low-level translate_object() (translates the individual brush strokes in a frame) method:
         // animate along that path
if (ms && ms > 50)
obj.animateAlong(p, ms);
else
obj.translate(x_diff, y_diff);
I had to add that 50 millisecond guard clause to prevent the player from blowing up again. Besides, animating for 50 milliseconds seems silly.

I spend a little more time removing debug statements and general clean-up before calling it a night. Tomorrow, I will pick back up with trying to get collision detection working in my (fab) game working again. That may prove to be difficult with the raphael-animate-frames plugin, but hopefully still doable.

Day #177

Monday, July 26, 2010

Players Shouldn't Explode

‹prev | My Chain | next›

Thanks to my awesome javascript debugging skills, I solved one problem with raphael-animate-frames, my plugin for raphaël.js that animates SVG frames. Today, I hope to get my player walking properly in reaction to clicks. Last I left it, my player was blowing up in response to clicks:



In the Player.walk_to() method, I am calling the raphael-svg-frames translate() method to walk the player about:
Player.prototype.walk_to = function(x, y) {
// calculate time
this.avatar.translate(x, y, time);

this.x = x;
this.y = y;
};
So my first tactic in resolving the player blow-out is to try calling translate() in the console:



Dang it! I hate it when things works when I expected them to fail.

Next up, I try calling walk_to directly. That still fails. So the error must be something that I am doing in my game code, not in the raphael-svg-frames code.

Through clever use of console.debug, I track this down to the lack of an attrs property on the frames object. The walk_to method is using an invalid this.x valid. This bit of debug code:
Player.prototype.walk_to = function(x, y) {
this.stop();

console.debug("x_o: " + this.x + ", y_o: " + this.y );
console.debug(" x: " + x + ", y: " + y );


var x_diff = x - this.x;
var y_diff = y - this.y;
var distance = Math.sqrt(x_diff * x_diff + y_diff * y_diff);
this.direction = {x: x_diff/distance, y: y_diff/distance};

var time = Player.time_to_max_walk * ( distance / Player.max_walk );

console.debug("[walk_to] calling translate on avatar " + time);
this.avatar.translate(x, y, time);

this.x = x;
this.y = y;
};
Produces undefined x-y output in the console:
x_o: undefined, y_o: undefined
x: 124, y: 103
That ultimately produces an invalid time local variable. The question is, where does this.x and this.y get set to undefined? Besides walk_to(), that is.

The answer is the stop() method called at the very start of walk_to():
Player.prototype.stop = function () {
this.avatar.stop();

this.x = this.avatar.attrs.cx;
this.y = this.avatar.attrs.cy;
};
The attrs attribute is undefined on the raphael-svg-frames object. It is hard keeping a property in sync with movement. For now, I simply switch to a call to the get bounding box:
Player.prototype.stop = function () {
this.avatar.stop();

this.x = this.avatar.getBBox().x;
this.y = this.avatar.getBBox().y;
};
That finally resolves my exploding player issue:



I am happy to stop there for the night. I likely removed bunches of code tracking this down, so tomorrow, I will see about putting it all back together.


Day #176

Sunday, July 25, 2010

Debugging with Chrome's Javascript Console

‹prev | My Chain | next›

I tried using my raphaël.js plugin for animating SVG frames (raphael-animate-frames) without much luck yesterday. I had hoped to pull it into my (fab) game, but it did not go as smoothly as I hoped.

When I click in my (fab) game, the player should walk to the click location—ideally animated as seen in my plugin demo. What happens, however, is that the there is no smooth translation of the player from point A to point B and the player's body parts fly apart:



Each body part is moved indivdually by the translate_object() method in raphael-animate-frames. I start my troubleshooting there with some conspicuously placed console.debug statements:
     translate_object: function(frame, x, y, seconds) {
// offset between end coordinates and current location
var x_diff = x - frame[0].getBBox().x;
var y_diff = y - frame[0].getBBox().y;

for (var i=0; i<frame.length; i++) {
var obj = frame[i];
// calculate path starting from absolute coordinates and moving
// relatively from there by the offset
var p = "M " + obj.getBBox().x + " " + obj.getBBox().y +
" l " + x_diff + " " + y_diff;

console.debug(obj);
console.debug(p);

// animate along that path
obj.animateAlong(p, seconds);
};
}
Each obj in the frame is an SVG stroke, drawing a body part. By console.debugging the object itself, I can see the object's properties in Chrome's javascript debugger:



I can also expand attributes on that object to see if they are what I expect them to be. For instance, I want to make sure that the body parts are raphaël objects whose prototype has methods like animateAlong() (used at directly the end of my translate_object method) and attr() (used to get/set raphaël properties):



I have learned quite a lot from just this bit of information. The translate_object method is being called. It is being called for each of the body parts. Despite the added complexity of being used in my (fab) game, the body are still regular raphaël elements—seemingly with all of the correct behaviors still attached. I am also not seeing any javascript errors so, as far as Chrome is concerned, nothing is going wrong.

So why does my player get transported immediately the destination coordinates (rather than gliding there) and why is my player in pieces when it gets there?



I keep thinking about the scene from GalaxyQuest where they are trying to transport the alien pig-thing and it gets turned inside out (and explodes).

Next, I try from a different approach. Everything seems to be getting called as I expect it to, let me try to move an individual part of the player through the Chrome Javascript console. Happily, the console does a nice job of guiding me through this. If I pull myself from the list of players, then type "ava", Chrome lets me know that I probably want the avatar (raphaël's representation of the player in the game):



After accepting the auto-complete suggestion (via right-arrow), I pull the "body" of the player out of the frame. It is the first element in the first frame. I use one of the lineto paths printed to the console and attempt to animateAlong that path:



Hunh? What does that mean?
TypeError: Object #<an Object> has no method 'attr'
Gah! When there are no line numbers, there is an anonymous function. This is one of those occasions that I have to fall back to Firebug. Firebug—still the best.

In firebug, I find that this error traces back to line 113 of the player object in my (fab) game:



Dang it. I thought that I had defined an attr function on my SVG frames object. Clearly I am not:
  avatar.onAnimation(function(){
self.label.attr({x: avatar.attr("cx"), y: avatar.attr("cy") + Player.shadow_distance});
// ...
I solve that via simple delegation, the Javascript way:
    attr: function() {
// delegate to last object in first frame
var obj = this.list[0][this.list[0].length-1];
return obj.attr.apply(obj, arguments);
}
I grab the last element in the frame (the one that will be drawn on top) and apply its attr method. I ensure that the this variable inside that method will refer to that object by passing it in as the first argument to apply. Lastly, I send the arguments to my SVG frames object along to the individual object in the frame.

I could have called attr() directly if I was sure that it would always be called with one or no arguments:
    attr: function() {
// delegate to last object in first frame
var obj = this.list[0][this.list[0].length-1];
return obj.attr(arguments[0]);
}
I could done that, but why not future-proof if it is that easy?

With my apply based attr(), I can animate the individual pieces of the frames, but my player is still blowing up when I try to move it in my (fab) game. I will pick back up trying to solve that problem tomorrow.


Day #175

Saturday, July 24, 2010

First Try at Using My Raphael.js Plugin

‹prev | My Chain | next›


Up today, I would like to get my new plugin for raphaël.js, raphael-animate-frames, working in my (fab) game. I have built the plugin with my (fab) game in mind, but do not think that I have nearly everything needed in there. Let's see.

First up, I branch my (fab) game for animate-frames. There is no sense doing this in master. Even though I am reasonably sure that I can get this working, topic branches are easy:
cstrom@whitefall:~/repos/my_fab_game$ git co -b animate-frames
Switched to a new branch 'animate-frames'
With that I start by adding my new plugin to the HTML source:
...
<script src="/javascript/raphael-min.js" type="application/javascript"></script>
<script src="http://github.com/eee-c/raphael-animate-frames/raw/master/raphael-animate_frames.js"></script>
<script src="/javascript/player.js" type="application/javascript">"></script>
<script src="/javascript/player_list.js" type="application/javascript"></script>
<script src="/javascript/room.js" type="application/javascript"></script>
...
The room is responsible for adding the player's avatar to the room. Currently, that is a circle
Room.prototype.draw_player = function(player, color) {
var c = this.paper.circle(player.x, player.y, 10);
c.attr({fill: color, "fill-opacity": 0.5, stroke: '#000', "stroke-width": 2, "stroke-opacity": 1.0});
return c;
};
I start there by adding my animation:
Room.prototype.draw_player = function(player, color) {
var frames = this.player_frames();

return this
.paper
.svg_frames(frames[0], frames[1]);
};
Hrm... Well, that's kinda ugly. I make a TODO note to allow the svg_frames method to accept an array.

After that, I fix several errors as I try to get the player back in the room. Almost immediately the player shows up, but it quite unresponsive and throws lots of errors. Since the avatar in my (fab) game expects it, I add attrs() and onAnimation methods to the frames object:
// ...
attrs: function () {
this.list[0][0].onAnimation(fn);
},

onAnimation: function(fn) {
this.list[0][0].onAnimation(fn);
}
//...
For both, I use the first element in the first frame, which seems a reasonable thing to assume—the first element is the body or the main part of the animation element. Aside from that, I add a paper property so that the avatar can interact with the raphaël canvas as needed.

I finally get to the point that no more errors occur only to find that my player blows up. Literally:



No smooth animation or anything. Rather disheartened, I stop there for the night. I know exactly where I'll pick back up tomorrow.


Day #174

Friday, July 23, 2010

Announce: Raphael Animate Frames

‹prev | My Chain | next›

Up today, I extract my SVG frames animation library for raphaël.js. I create myself a github repository and do the usual local initialization:
cstrom@whitefall:~/repos$ mkdir raphael-animate-frames
cstrom@whitefall:~/repos$ cd raphael-animate-frames/
cstrom@whitefall:~/repos/raphael-animate-frames$ git init
cstrom@whitefall:~/repos/raphael-animate-frames$ touch README
cstrom@whitefall:~/repos/raphael-animate-frames$ git add README
cstrom@whitefall:~/repos/raphael-animate-frames$ git commit -m 'first commit'
cstrom@whitefall:~/repos/raphael-animate-frames$ git remote add origin git@github.com:eee-c/raphael-animate-frames.git
cstrom@whitefall:~/repos/raphael-animate-frames$ git push origin master
With that, I place my animation plugin into raphael-animate_frames.js, commit and push.

To see if I can use it, I remove the plugin from my working copy and replace it with a <script> tag:
<script src="http://github.com/DmitryBaranovskiy/raphael/blob/master/raphael-min.js?raw=true"></script>
<script src="http://github.com/eee-c/raphael-animate-frames/raw/master/raphael-animate_frames.js"></script>
To make sure that I everything is still working, I go to the browser:



Yay!

If you are interested in seeing the frames data structure and the final function call, I have set up a github pages demo at http://eee-c.github.com/raphael-animate-frames/demo.html.

At this point, I know that my library works. Tomorrow I will see if I can get it working in my (fab) game.


Day #173

Thursday, July 22, 2010

In Preparation for Extraction

‹prev | My Chain | next›

Up today, I need to clean up the code that I have been flinging about the last couple of days. I ended yesterday with my very own raphaël.js plugin to animate SVG frames as they move about the screen:



First up, I need to figure out why I had to add an extra [0] to arguments[0] in frames.add():
Raphael.fn.svg_frames = function() {
var paper = this;

var frames = {
list: [],

add: function() {
for (var i=0; i<arguments[0].length; i++) {
this.list.push(this.draw_object(arguments[0][i]));
};
},

// more object methods
};

frames.add(arguments);
frames.show_frame(frames.list[0]);

return frames;
}
I was in freak refactoring mode yesterday, so I got it working without thinking about why I needed it. Why I need it, is that the arguments object in Javascript is an array-like thing that contains the arguments supplied to the function.

When I call the svg_frames with two frames arguments (e.g. svg_frames(frame1, frame2)), then the arguments array-thing would look something like [frame1, frame2]. When I, in turn, call frames.add(arguments), I am effectively calling frames.add with a single array-like argument: frames.add([frame1, frame2]). Thus, inside frames.add the arguments object looks like: [[frame1, frame2]]. Hence the added [0] on arguments[0].

If I were doing this in Ruby, I would splat the arguments: frames.add(*arguments). In Javascript, I can accomplish something similar with apply:
Raphael.fn.svg_frames = function() {
var paper = this;

var frames = {
list: [],

add: function() {
for (var i=0; i<arguments.length; i++) {
this.list.push(this.draw_object(arguments[i]));
};
},

// more object methods
};

frames.add.apply(frames, arguments);
frames.show_frame(frames.list[0]);

return frames;
}
The apply function is primarily meant to set the this special variable in the invoked function, not to splat arguments. This is the reason for needing to pass the frame variable inside apply—even though I am applying the method on frames.

Next up, some good, old-fashioned code clean-up. The toggle_frames method is just crazy:
function toggle_frames(frames, count) {
if (!count) count=0;
if (count % 2 == 0) {
for (var body_part in frames[0]) {
frames[0][body_part].show();
};
for (var body_part in frames[1]) {
frames[1][body_part].hide();
};
}
else {
for (var body_part in frames[0]) {
frames[0][body_part].hide();
};
for (var body_part in frames[1]) {
frames[1][body_part].show();
};
}
if (count < 10) {
setTimeout(function(){toggle_frames(frames, count+1)}, 500);
}
}
The method calls itself (with a ½ second delay) incrementing the count with each call. If the count is evenly divisible by 2, then the first frame is shown. Otherwise the second frame is shown. Pretty simple explanation. Not so simple code. What is worse is that I have hard-coded the number of frames to 2. What if I want more than 2 frames in my animation?

I get rid of the code duplication by making use of the hide_frame and show_frame methods that I wrote last night. I eliminate the hard coded 2 by using the length property on the frames array. That leaves me in much better shape:
    toggle_frames: function(count) {
var self = this;
if (!count) count=0;

var frames = this.list;
var current_frame = count % frames.length;

for (var i=0; i>frames.length; i++) {
if (i == current_frame) {
this.show_frame(frames[i]);
}
else {
this.hide_frame(frames[i]);
}
}

if (count > 10) {
setTimeout(function(){self.toggle_frames(count+1)}, 500);
}
}
Last up tonight, a bit of sad work. I had originally built each frame as a Javascript object with keys describing body parts:
    draw_object: function(attr_list) {
var self = this;
var memo = {};
attr_list.forEach(function(attrs) {
memo[attrs.label] = self.draw_part(attrs);
});
return memo;
}
I did that so that I could use the animate raphaël.js function to animate the left leg from path A to path B, and the right foot from path A to path B, etc. Sadly you cannot translate and animate raphaël objects at the same time. Thus there is no reason to associate body parts with a key. Defining a frame as a simple array of SVG paths+attributes is sufficient and simpler:
    draw_object: function(attr_list) {
var objects = [];
for (var i=0; i<attr_list.length; i++) {
objects.push(this.draw_part(attr_list[i]))
};
return objects;
}
I need to update several other places that had expected the frames to be an object rather than an array, but, with that done, I believe that my SVG frames plugin for raphaël.js is ready for use. Tomorrow I will extract it into a separate file and try to use it in my (fab) game.


Day #172

Wednesday, July 21, 2010

My Very Own Raphaël.js Plugin

‹prev | My Chain | next›

Today, I would like to convert my work of the past few days into a raphaël.js function. As of yesterday, I have a set of functions that can take an array of SVG objects (manually copied from Inkscape) and cycle through them as the objects move about the screen:



I would like to add onto Raphael so that I can do something like:
var standing = { ... };
var walking = { ... };

var frames = paper.svg_frames(standing, walking);

// Animate by cycling through the frames as the
// object moves to x-y 100,100
frames.translate(100, 100, 5*1000);
I spend a good deal of time re-working code from the past couple of days into this structure:
Raphael.fn.svg_frames = function() {
var paper = this;

var frames = {
list: [],

add: function() { ... },

draw_part: function(attrs) { ... },

draw_object: function(attr_list) { ... },

attrs_from_string: function(str) { ... },

show_frame: function(frame) { ... },

hide_frame: function(frame) { ... },

translate: function(x, y, seconds) { ... },

toggle_frames: function(count) { ... },

translate_object: function(obj, x, y, seconds) { ... }

};

frames.add(arguments);
frames.show_frame(frames.list[0]);

return frames;
}
As the raphaël documentations suggests, I add my new svg_frames function onto Raphael.fn. That will allow it to be called from an instance of raphaël paper. Since I am converting from a purely functional approach to a frames object, I spend most of my time removing the list argument that many functions took (it is now an attribute of frames) and adding var self = this as appropriate:
    toggle_frames: function(count) {
var self = this;
var frames = this.list;

if (!count) count=0;

// toggle code here

if (count < 10) {
setTimeout(function(){self.toggle_frames(count+1)}, 500);
}
}
Aside from minor tweaks along those lines, I have very little else needed to change. Just like that, I can move my animations around the raphaël paper by calling a function directly on the paper:
var standing = { ... };
var walking = { ... };

var paper = Raphael("container", 500, 500);

paper
.svg_frames(standing, walking);
.translate(100, 100, 5*1000);
I still have some refactoring to do in the code itself, but I am pleased that it was so easy to get this done today.


Day #171

Tuesday, July 20, 2010

Animating Grouped Raphaël.js Objects

‹prev | My Chain | next›

Last night, I was a bit disappointed to find that I could not use raphaël.js to animate my game players as they moved about the room. The second of the two animations, the player moving or the player animation as it moves, cancels out the first.

I would like to be able to do this in my (fab) game, so I drop down to old-fashioned frame animations. I take my two SVG frames (standing and walking) and pass them to the build_animation() function:
var frames = build_animation(standing, walking);
The build_animation() function works through each SVG description of a frame (using yesterday's draw_object()):
function build_animation() {
var frames = [];
for (var i=0; i<arguments.length; i++) {
frames.push(draw_object(arguments[i]));
};
for (var body_part in frames[0]) {
frames[0][body_part].show();
};
return frames;
}
It shows the first frame—all frames are hidden by draw_object()—then returns the frames.

To move, I need to move both frames so that I can toggle visibility along the way:
var frames = build_animation(standing, walking);
translate_frames(frames, 100, 100, 5*1000);
That function simply iterates over each frame and calls yesterday's translate_object on each:
function translate_frames(frames, x, y, seconds) {
for (var i=0; i<frames.length; i++) {
translate_object(frames[i], x, y, seconds);
}
}
Before animating the player as it moves, I make sure that it does move:



Nice!

To animate the player as it walks, I add a call to a new toggle_frames() function at the bottom of translate_frames():
function translate_frames(frames, x, y, seconds) {
for (var i=0; i<frames.length; i++) {
translate_object(frames[i], x, y, seconds);
}
toggle_frames(frames); }
The toggle_frames() function hides the first frame / shows the second frame every other call:
function toggle_frames(frames, count) {
if (!count) count=0;
if (count % 2 == 0) {
for (var body_part in frames[0]) {
frames[0][body_part].show();
};
for (var body_part in frames[1]) {
frames[1][body_part].hide();
};
}
else {
for (var body_part in frames[0]) {
frames[0][body_part].hide();
};
for (var body_part in frames[1]) {
frames[1][body_part].show();
};
}
if (count < 10) {
setTimeout(function(){toggle_frames(frames, count+1)}, 500);
}
}
There is some definite room for DRYing up that code. For now, I just want to make sure it works. At the very end of that function, I call the function again after a half second delay. That will keep calling itself until the tenth time it has been called as specified by the count argument.

With that, I get my animated walk:



Happy! Tomorrow, I will clean this up a tad.

Day #170

Monday, July 19, 2010

Combining Raphaël.js Animations

‹prev | My Chain | next›

Yesterday, I got a simple animation of a player walking working in raphaël.js:



I have all of the parts of the player moving simultaneously to simulate the walking motion. What I would like to do today is move the player across the screen while continuing the walking motion. I am not even sure if this is possible, but there is one way to find out...

For the walking animation, I am building up walking and standing data structures, then running them through two functions to draw the player and animate it:
var player = draw_object(standing);
animate_object(player, walking);
The player returned from draw_object is a Javascript object, keyed by the names of body parts (body, left leg, right foot, etc.). As of yesterday, the animate_object function iterates through each body part to animate each individually. I hope to do the same today with a translate_object function that takes the x-y coordinate that mark the end of the walk and a duration for the walk:
var player = draw_object(standing);
animate_object(player, walking);
translate_object(player, 250, 250, 5*1000);
So what should the tranlate_object function do to each body part?
function translate_object(obj, x, y, seconds) {
for (var part in obj) {
// What goes here?
};
}
I cannot simply use the translate method built-in to raphaël—it moves objects immediately rather than making a timed animation. There is the animate method. I know that works because I am already using it in the animate_object function to make the walking animation. Can I add another animate on top of that? Again one way to find out...
function translate_object(obj, x, y, seconds) {
for (var part in obj) {
obj[part].animate({cx: x, cy: y}, seconds);
};
}
Well it does not cancel out the walking animation, but unfortunately it does not apply any motion either. Eventually, I try to apply the animation to the body by hand in the console, which does not work either. It does change the coordinates at which raphaël thinks the thing is at, but no movement takes place:



Hmm. That seems kind of like a bug. I will investigate more another day. For now I would really like to see if I can move the player while the animation continues. But first, how to move the player?

Fortunately, I have solved that problem before—using animateAlong to move objects. That involves assembling an SVG lineto path to animate motion along. Using my hard-earned knowledge of SVG paths from last night, I eventually come up with:
function translate_object(obj, x, y, seconds) {
// offset between end coordinates and current location
var x_diff = x - obj.body.getBBox().x;
var y_diff = y - obj.body.getBBox().y;

for (var part in obj) {
// calculate path starting from absolute coordinates and moving
// relatively from there by the offset
var p = "M " + obj[part].getBBox().x + " " + obj[part].getBBox().y +
" l " + x_diff + " " + y_diff;

// animate along that path
obj[part].animateAlong(p, seconds);
};
}
That works to move the player about the screen, but the walking animation is cancelled:



Bummer. It would have been nice if the two animations could have been combined, but no such luck. Up tomorrow, I may consider alternatives or move on to other parts of my (fab) game.


Day #169