A 2D physics engine written from scratch in Python, with a small basketball game built on top of it. A small project I made in high school, coded by hand before AI.
Left: the example scene. Right: the basketball game. The dot is the mouse (red when clicking).
Everything is in Physics_Engine.pyw. Lengths are in meters and masses in kg (the window is 5 m wide).
Motion. Each frame, we sum the forces
Collision detection. A ball collides with a round wall when the distance between the centers is smaller than the sum of the radii. For a rectangle, we take the point of the rectangle closest to the ball's center (by clamping the center's coordinates to the rectangle) and check if it is closer than the radius. In both cases we get the normal
Collision response. We first push the ball back out of the wall along
Finally, if the sum of the forces points into the wall, we add the normal reaction
Needs Python and pygame.
python Physics_Engine.pyw # example scene
python Basketball.pyw # the gameA scene is a few lines at the end of the file. Forces go in the scene's run function, which is called at each frame.
a = Scene()
ball = a.addMovingObj(Ball(0.2, 10, pos=Vect2(1, 3))) # radius, mass
ball.velocity = Vect2(3, 0)
a.addStaticObj(Wall(Vect2(5, 0.5), Vect2(0, 0.5))) # size, position
a.addStaticObj(RoundWall(1, Vect2(3, 1.5))) # radius, position
a.run()In both scenes, holding the mouse pushes the ball away from the cursor. In the basketball game, touch the green target as many times as possible in 60 seconds; the obstacles move after each point.
The same code works for side view scenes (with gravity) and top view scenes (like minigolf, with friction instead of gravity). For the moment it only handles moving/static collisions, not moving/moving ones.