I am trying to make a snake game in javascript, but I am struggling with collision detection. I have tried various methods so far, but in desperation I decided to keep all the positions of the segments in each frame, and then check if there are any duplicates before animating the next one. This method was not successful, unfortunately.
Perhaps this is due to a misunderstanding of how JS handles arrays. For some time I used if(x in y) , but from what I can say, it returns if the same object is in the array.
Here is a live demo: http://jsfiddle.net/AScYw/2/
Here is code that is easier to read: http://pastebin.com/ygj73me6
This code is in the snake object as a function of collide .
this.collide = function(){ for(var z=0; z<this.positions.length-1; z++){ for(var q=z+1; q<this.positions.length-1; q++){ return this.positions[z][0] == this.positions[q][0] && this.positions[z][1] == this.positions[q][1]; } }
source share