I'm trying to make a snake game in javascript, but I am struggling with collision detection. I've tried various methods so far, but in desperation, have settled storing all the positions of the segments each frame then checking whether there are any duplicates before animating the next. This method hasn't proved successful either unfortunately.
Perhaps this is due a misunderstanding of how JS treats arrays. For a while I was using if(x in y)
but from what I can tell that returns if the exact same object is in an array.
Here is the live demo: http://jsfiddle.net/AScYw/2/
Here is the code more easily read: http://pastebin.com/ygj73me6
The code in question is in the snake object, as the function 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];
}
}