-1

I'm making a simple game where I bounce and image off the sides of the screen (a bit like the ball bounces in Pong) but I can't seem to the the bouncing part to work. Instead of bouncing of the edges of the screen it is going right through it. The related code is below:

while (mainloop):

    milliseconds = clock.tick(FPS)
    seconds = 1 / float(milliseconds)

    square.loc_x += 35 * seconds
    square.loc_y += 35 * seconds

    # I'm guessing the problem lies in the code below but I can't seem to spot it
    if square.loc_y >= 440 or square.loc_y <= 1:
        print square.loc_y >= 440 or square.loc_y <= 1
        square.loc_change_y = square.loc_change_y * -1 * seconds
    elif square.loc_x >= 600 or square.loc_x <= 1:
        print square.loc_y >= 440 or square.loc_y <= 1
    square.loc_change_x = square.loc_change_x * -1 * seconds

    square.loc_x += square.loc_change_x * seconds
    square.loc_y += square.loc_change_y * seconds
  • You need to explain more than "can't seem to the the bouncing part to work". How is it not working? What have you tried to do to fix it? How do you want it to work? Please edit your question to include this information. Also, please remove all code that's not related to the problem. – House Aug 15 '13 at 17:37

1 Answers1

1

You're adding positive constants (+35) to your square's location:

square.loc_x += 35 * seconds
square.loc_y += 35 * seconds

You should only be adding your square's velocity to its position, like you do in the last two lines:

square.loc_x += square.loc_change_x * seconds
square.loc_y += square.loc_change_y * seconds

That should fix your immediate issue, but I have a couple more notes:

Since it looks like you're using a variable timestep, you might find that your ball will leave the screen with enough force that it won't be able to come back into the play area in a single tick. So you will end up reversing its direction, moving back toward the play area, then since it's still out of bounds, you will re-reverse its direction and move it further out of bounds. This will cause your ball to go back and forth along the edge of the screen. To prevent this, simply split your left/right and top/bottom bound checking in to 4 statements instead of 2. If the ball goes off the top, make sure it's vertical speed is pointing down into the play area, don't just assume the ball is moving up.

And a quick thing. When you are trying to reverse the direction of the ball, you are multiplying my -1, and by the number of seconds passed (also known as delta time):

square.loc_change_x * -1 * seconds

You shouldn't need to multiply by the number of seconds that have passed. You're simply trying to reverse the ball's direction. Later on, you will apply the ball's current speed to the position using the delta time.

John McDonald
  • 6,746
  • 2
  • 31
  • 45