Search code examples
javascripthtmlcollision-detectionhtml5-canvas

Collision detection in JS


I'm recreating an old game, similar to Tron, in HTML5 canvas+JS. The main difference is that the snakes don't turn in right angles, they can move in curves (the name's Achtung Die Kurve).

I need to detect collisions, and I don't know how. The rules are really simple, and everything I come up with or read about looks needlessly complicated. Collisions occur when:

  1. A snake runs into another snake's body (or its own) head-first (I emphasize that because, in a very early experiment, my snakes' heads crushed backwards into their own "necks" as soon as they moved :P).

  2. A snake runs into a wall (no inner walls).

How should I go about this? I'm willing to add whatever data is needed to my objects.


Solution

  • First off, thanks everyone for your responses! I read what you posted, read a little more around, did some thiking and decided to do the following:

    I'm going to keep a bytemap representing the game area, and every time a position is occupied, add 1 to the value. Then, I'm going to check in the 3 "outer" corners of the 4 corners of the snake's head (the "inner" corner collides with the rest of the body) for != 1 values.

    I think I'll use an invisible canvas and the alpha value to keep my code simple.

    Sorry I wrote my own answer to accept: I think it's important to keep a record of the actual solution I'll implement, and none of the answers fully details my decission.