开发者

Javascript Collision Detection

I'm trying to make a snake game in javascript, but I am struggling with collision detection. I'v开发者_如何学编程e 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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜