简体   繁体   中英

Javascript Collision Detection

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];
                }
            }

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.

  1. You are dropping out of the loop the first comparison. You will want to do something like if (something overlaps) return true then outside of both loops return false if you make it through successfully
  2. You will want to make sure that the z segment != q segment or you will always have a collision

Looks cool. Lets see Mario next;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM