Reputation: 65
As a bit of an exercise I've been trying to follow a Java tutorial while converting it to python, as it makes me think a bit more than just copying what the tutorial types on the screen.
I'm up to this part of the tutorial: https://www.youtube.com/watch?v=FuqCfxZcFCI&list=PL87AA2306844063D2&index=6
He makes a ball drop from y = 25, hit the bottom of the window and bounce up, using physics formulae v = u+at and s = s+vt + 1/2at^2. He then shows that because the ball doesn't lose energy when it hits the ground, it always returns to the same height it was dropped from. To fix this, he adds an energy loss formula.
So I recreated his code in python, but as I was testing it, I noticed that even without the energy loss formula, my ball behaves more like a real life ball, bouncing lower and lower each time.
Can anyone spot what's causing this? Thanks!
import pygame
# pygame window
WIDTH, HEIGHT = 800, 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ball Game!")
FPS = 60
# physics variables
GRAVITY = 15
ENERGY_LOSS = 0.65
dt = 0.2
# player position variables
x = 400
y = 25
dx = 0
dy = 0
radius = 20
#colours
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
def draw_window():
WINDOW.fill(WHITE)
pygame.draw.circle(WINDOW, GREEN, (x, y), radius)
pygame.display.update()
def main():
clock = pygame.time.Clock()
global x
global y
global dx
global dy
run = True
while run:
clock.tick(FPS)
if y > HEIGHT-radius-1:
y = HEIGHT - radius - 1
# dy = dy * ENERGY_LOSS # Why is there energy loss without the formula!?!?!
dy = -dy
else:
# velocity- acceleration formula
dy += GRAVITY * dt
# position formula
y += dy * dt + (0.5 * GRAVITY * dt ** 2)
draw_window()
if __name__ == '__main__':
main()
Upvotes: 0
Views: 237
Reputation: 12140
Just logically dy
is a change of y
over time (dt
). So it should be:
# velocity- acceleration formula
dy += GRAVITY * dt
# change of position
y += dy * dt
That works as expected for me.
While:
y += dy * dt + (0.5 * GRAVITY * dt ** 2)
kinda resembles the position formula, except it should be:
y = y_0 * t + (0.5 * GRAVITY * t ** 2)
Where t
is a passed time and y_0
is the initial position.
Upvotes: 1
Reputation: 302
Since y > HEIGHT-radius-1 EQUALS 25 > 600-20-1 EQUALS 25 > 579 EQUALS FALSE
dy += GRAVITY * dt EQUALS 0 += 15 * 0.2 EQUALS dy = 3
dy * dt + (0.5 * GRAVITY * dt ** 2) = 3 * 0.2 + (0.5 * 15 * 0.2**2) = 0.6 + ( 7.5 * 0.04) = 0.6 + 0.3 = 0.9
Therefore, y = 0.9 after 1 run. That's why it loses height.
Upvotes: 0