Javascript Collision Detection

孤街浪徒 提交于 2019-12-09 06:12:26

问题


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

回答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 ;)



来源:https://stackoverflow.com/questions/7047928/javascript-collision-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!