6

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];
                }
            }
2
  • 1
    This game sure is easy with collision detection disabled! Commented Aug 13, 2011 at 1:42
  • @PiPeep Yeah isn't it great?! Commented Aug 13, 2011 at 1:47

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure if I quite understand your first point, what do you mean I am dropping out of the loop? And doesn't initiating q at z+1 ensure they won't be the same? Thanks for the help! I'm not sure if I'm anywhere near ready to remake mario. D: Maybe tetris first.
Your return statement gets called the first time through the loop, so you only end up checking one segment.
@thedaian you mean it exits the loop regardless of it returning true? I've changed the code so that the return is called after it passes a condition, but it is now always returning true.
@thedaian Ah! I figured it out. In the initiate function I was placing two segments on top of one another. It is now working wonderfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.