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];
}
}
Collision detection also known as hit testing is one of the most commonly and widely used terminology in web development to detect or sense tow hitting or colliding objects on screen.
If both the horizontal and vertical edges overlap we have a collision. We check if the right side of the first object is greater than the left side of the second object and if the second object's right side is greater than the first object's left side; similarly for the vertical axis.
One of the simpler forms of collision detection is between two rectangles that are axis aligned — meaning no rotation. The algorithm works by ensuring there is no gap between any of the 4 sides of the rectangles. Any gap means a collision does not exist.
Collision detection is the basics of entities interaction on canvas. Imagine you have a Player Character (PC) that's walking through a maze and you'd like to know if this PC bumps into a wall or can keep on going.
You function here needs a little work and it may fix your problem.
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];
}
}
}
2 things are wrong.
Looks cool. Lets see Mario next ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With