Hell stormer
Hell stormer

Reputation: 483

Bouncing Ball doesn't come back pygame

import pygame

pygame.init()
width = 400
hight = 600
screen = pygame.display.set_mode((width, hight))
pygame.display.set_caption("Engine")
dot = pygame.image.load("KreisSchwarz.png")
clock = pygame.time.Clock()
running = True
WHITE = (255, 255, 255)

# Set (x, y) for Dot
def updateDot(x, y):
    screen.blit(dot, (x, y))

# Display Dot at (x, y)
def update(fps=30):
    screen.fill(WHITE)
    updateDot(x, y)
    pygame.display.flip()
    return clock.tick(fps)

# Quit if User closes the window
def evHandler():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            running = False

yKoords = []
(x, y) = (300, 200)
t = 1 # time variable
a = 2 # acceleration constant
tol = 40 # tolerance
i = 0 # just some iterator

# MAIN LOOP
while running:
    evHandler()
    update()
    y += a * (t ^ 2)
    t += 1
    yKoords.append(int(y))
    i += 1

    if (y < (hight + tol)) and (y > (hight - tol)):
        y = 580
        yKoords.reverse()
        update()

        for q in range(i):
            evHandler()
            y = yKoords[q]
            update()
            if q == i - 1: # Because i didn't write the Part for the Dot coming back down
                running = False

This is my Code for a Ball accelerating down and then jumping back up. My Problem is, that the code works fine until the if statement. There the Programm just displays the Ball at the last position in yKoords and waits until the for loop finishes. If i remove the for loop the Ball gets displayed at y=580 and stops but thats fine.

Please help i have no idea whats wrong about this.

Upvotes: 3

Views: 185

Answers (1)

Rabbid76
Rabbid76

Reputation: 211135

Don't do a separate process loop in the main loop.

It is sufficient to invert the direction, when the ball bounce on the ground (abs(y - hight)) or the ball reaches the top (t == 0).

direction = 1
while running:
    evHandler()
    update()
    y += (a * (t ^ 2)) * direction
    t += direction

    if abs(y - hight) < tol:
        y = 580
        t -= 1
        direction *= -1
    elif t == 0:
        direction *= -1

Upvotes: 0

Related Questions