Saturday, June 12, 2010

Collision Detection in Raphaël.js

‹prev | My Chain | next›

I spend a bit of time fixing up bits and pieces of my (fab) game earlier. Now I would like to start investigating collision detection in the game.

For now, I would like to explore collision detection in raphaël.js. Ultimately, I think collision detection has to take place in the backend, but I am just playing with frontend detection for now.

After looking through the raphaël.js source code for a while with no luck, I resort to Google. Ultimately, I come across a post on Stackoverflow that suggests looking at document.elementFromPoint.

I manually specify the offsetTop and offsetLeft (as 8 / 8) and get this working with:
//...
avatar.onAnimation(function(){
var c_el = document.elementFromPoint(avatar.attr("cx") + 8,
avatar.attr("cy") + 8);

console.debug(c_el);
console.debug(self.avatar);
if (c_el != self.avatar.node &&
c_el != self.avatar.paper) {
console.debug("collision!");
this.stop();
}
//..
I grab the collision element and store it in c_el. I then check to make sure that the colliding element is not me and not the raphaël.js paper. If it is some other element, then I stop my walk.

With that, the player can move about the room, but, if I cross paths with another player, I stop immediately:


Unfortunately, the player is now stuck. Any attempt to move results in an immediate collision. Ah well, something to work tomorrow.

Day #132

1 comment:

  1. fwiw, collision detection is a hard problem no matter what you're implementing it with. In flash I've done it by looking at the pixels on the screen, but I don't think that's a great way to do it ;) I'm interested to see what you come up with!

    ReplyDelete