Back

Simple Harmonic Motion

Script description

This script uses the pygame library to draw two squares doing a simple harmonic ocillation with a phase difference of π/2 perpendicular to each other. It also draws a circle at the x, y of the two squares.

Result

SHM

It is proven that the circle performs uniform circle motion.

Source Code

import math
import pygame
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("simple harmonic motion")
FPS = 60

run = True
x1 = WIDTH/2
y2 = HEIGHT/2

A = 200
f = 0.5
Omega = 6.28 * f

totalFrames = 0

while run:
    totalFrames += 1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    y1 = A * math.sin(Omega * totalFrames / 60) + HEIGHT / 2
    x2 = A * math.cos(Omega * totalFrames / 60) + WIDTH / 2


    WIN.fill((0, 0, 0))

    pygame.draw.line(WIN, (255, 255, 255), (WIDTH/2, 0), (WIDTH/2, HEIGHT))
    pygame.draw.line(WIN, (255, 255, 255), (0, HEIGHT/2), (WIDTH, HEIGHT/2))

    pygame.draw.line(WIN, (255, 0, 0), (WIDTH/2, HEIGHT/2), (x1, y1))
    pygame.draw.rect(WIN, (100, 100, 100), pygame.Rect(x1-15, y1-15, 30, 30))

    pygame.draw.line(WIN, (255, 0, 0), (WIDTH/2, HEIGHT/2), (x2, y2))
    pygame.draw.rect(WIN, (100, 100, 100), pygame.Rect(x2-15, y2-15, 30, 30))

    pygame.draw.line(WIN, (0, 255, 0), (WIDTH/2, HEIGHT/2), (x2, y1))
    pygame.draw.circle(WIN, (255, 255, 255), (x2, y1), 5)

    pygame.draw.circle(WIN, (255, 255, 255), (WIDTH/2, HEIGHT/2), A, 1)

    pygame.display.update()
    pygame.time.delay(16)

pygame.quit()