Javascript Conflict Detection

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]; } } 
+6
source share
1 answer

Here you need a little work and this can solve 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.

  • You drop the first comparison from the loop. You will want to do something like if (something overlaps), return true, and then return false outside of both loops if you succeed
  • You need to make sure that segment z segment! = Q or you will always encounter

It looks cool. Let's look at the following Mario :)

+5
source

Source: https://habr.com/ru/post/894960/


All Articles