I have a collision method implemented through the use of slick2d. When ever the snake collides with the apple, it causes the apple to be rendered in multiple places before the snake moves further along.

    if(checkCollision() == true){
        x -= 1;

        snakes.add(new Point(x, y));

And heres the locate method to move the apple in a random position:

public void locateApple() {
       int r = (int) (Math.random() * RAND_POS);
       applePoint.setX((r * DOT_SIZE));
       applePoint.setY((r * DOT_SIZE));


This is in my update() method, which is probably causing the problem, how can I run this code only once? SO that once it collides, it moves the apple in a new position with out executing multiple times.


One way would be to keep track of the collision state for the current and previous frames, and only trigger a collision when there is a collision on the current frame, but there was no collision on the previous frame.

This way, once a collision has been triggered, there will need to be at least one frame of non-collision before it triggers again. Simply put:

bool previouslyColliding = false;
bool currentlyColliding = false;

public void update()
    currentlyColliding = checkCollision();
    if(currentlyColliding && !previouslyColliding) 
        // Handle collision here
    previouslyColliding = currentlyColliding;

If that doesn't solve it, it's most probably because of a problem with checkCollision() returning true when it shouldn't.

  • \$\begingroup\$ This worked great, thanks and also thanks for explanation! \$\endgroup\$ – Sun May 16 '12 at 19:22
  • \$\begingroup\$ Huh so your collision detection algorithm checks each object multiple times per update pass? \$\endgroup\$ – Roy T. May 16 '12 at 19:55

Although you're not giving too much info I guess this is happening:

Update 1:
the apple collides with the snake
the apple is removed
a new apple is placed at X
Draw 1:
the apple is drawn at X
Update 2:
it turns out that there was already something at X so the apple immediately collides 
the apple is removed
a new apple is placed at Y
Draw 2:
the apple is drawn at Y

Repeat until the new apple is placed on a free position

The chance of this happening is getting more and more likely as the snake grows, so you might see your apple flash at 3,4,5 places before it finding a free spot.

If this is the case David Gouveia's answer is not sufficient. To solve this you should modify your findApple method to only place it on a free position.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.