Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am trying to make a breakout game where you have a paddle and a ball bounces around breaking bricks. The problem is that if the ball touches the corner of player it goes inside of player. I change the dx, -dx, dy, -dy, etc. in order to change the ball position so it looks like it bounces off of the player or window.

Here I check collision between ball and window. x,y,dx,dy are ball position and speed.

public void BallWCollision()
{
    //dx, dy is ball speed

    if(x <= 0){   //if ball goes right of screen 
      dx = -dx;
    }
    else if(x >= Main.WINDOW_WIDTH){  //if ball goes left of screen
      dx = -dx;
    }    

    if(y <= 0){    //if ball goes top of screen
      dy = -dy;
    }
    else if(y >= Main.WINDOW_HEIGHT){  //if ball goes bottom of screen
      dy = -dy;
    }
}

Here I check collision between player and ball. If the ball touches the player then change ball dy.

public void playerBallCollision(Ball b)
{
    if(player.getBounds().intersects(b.getBounds())){  //if player and ball touch each other
      b.setDy(-b.getDy());
    }
}
share|improve this question

1 Answer 1

There are many specific circumstances related to your code (that you haven't posted). For instance, do you update position before or after checking for collisions? Do you always apply changes to position, or are they sometimes skipped? Do you apply any extra position change in order to resolve a collision? When your ball gets "inside" player, is it still moving in the x direction? After changing direction, are you certain your ball will not bounce a second time?

That last one is most important. If a ball strikes the corner of your paddle, then simply changing the sign of dy probably won't resolve the collision. The ball could be too far along in the y direction to move out of the paddle before the next update. So on that next update, it will collide again, and it will reverse direction again. This process will repeat indefinitely.

What you need to do is not simply change direction of motion, but guarantee that the collision is resolved. You may have to separately detect a region of collision, where a corner is different from the front, is different from the side, etc. For the case of the corner, you may only need to reverse both dx and dy. You may need to arbitrarily move the ball out of collision with the paddle. It all depends on your specific implementation.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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