Manuel Medina
Manuel Medina

Reputation: 409

Python:Pygame: How to animate a ball to move in a sin() like pattern?

How would you make a ball move in a repetitive wavey pattern just like a sin() graph does?

Upvotes: 1

Views: 4249

Answers (1)

agoebel
agoebel

Reputation: 401

You can use a counter, pygame's Clock, or just pygame.time.get_ticks to figure out the time. Here's some sample code to get you started.

import math
import pygame

pygame.init()
screen = pygame.display.set_mode((400,400))

while True:
    t = pygame.time.get_ticks() / 2  % 400 # scale and loop time
    x = t
    y = math.sin(t/50.0) * 100 + 200       # scale sine wave
    y = int(y)                             # needs to be int

    screen.fill((0,0,0))
    pygame.draw.circle(screen, (255,255,255), (x, y), 40)

    pygame.display.flip()

Upvotes: 5

Related Questions