Make 2D physic engine using python and pygame. Implement: 1. Advanced physics 2. Shapes…
- User
Make 2D physic engine using python and pygame.
Implement:
- Advanced physics
- Shapes
- UI
- Assistant
Make 2D physic engine using python and pygame.
Implement:
Certainly! Creating a 2D physics engine using Python and Pygame is an engaging project that can deepen your understanding of physics simulations and game development. Below, I'll guide you through building a basic physics engine with advanced features, custom shapes, and a user interface. We'll cover:
Let's get started!
First, ensure you have Python installed. Then, install Pygame using pip:
pip install pygame
Create a new Python script and import the necessary libraries:
import pygame
import sys
import math
from pygame.math import Vector2
We'll simulate:
Create a base class for all physical objects:
class PhysicsObject:
def __init__(self, mass=1.0, position=(0, 0), velocity=(0, 0)):
self.mass = mass
self.position = Vector2(position)
self.velocity = Vector2(velocity)
self.acceleration = Vector2(0, 0)
self.forces = Vector2(0, 0)
self.inv_mass = 1 / mass if mass != 0 else 0
def apply_force(self, force):
self.forces += force
def update(self, dt):
# Update acceleration based on forces
self.acceleration = self.forces * self.inv_mass
# Update velocity and position
self.velocity += self.acceleration * dt
self.position += self.velocity * dt
# Reset forces for the next frame
self.forces = Vector2(0, 0)
Add gravity as a constant force:
GRAVITY = Vector2(0, 980) # Pixels per second squared
def update(self, dt):
# Apply gravity
self.apply_force(self.mass * GRAVITY)
# Continue with the usual updates
super().update(dt)
Detect collision with the ground and respond:
def check_ground_collision(self, ground_y):
if self.position.y + self.shape.get_bottom_offset() >= ground_y:
self.position.y = ground_y - self.shape.get_bottom_offset()
self.velocity.y *= -0.7 # Apply restitution coefficient
Implement collision detection between objects (e.g., circles):
def check_collision(self, other):
distance = self.position.distance_to(other.position)
min_distance = self.shape.radius + other.shape.radius
if distance < min_distance:
# Simple collision response
overlap = min_distance - distance
direction = (self.position - other.position).normalize()
# Separate the objects
self.position += direction * (overlap / 2)
other.position -= direction * (overlap / 2)
# Exchange velocities (elastic collision)
self.velocity, other.velocity = other.velocity, self.velocity
We'll create base classes for different shapes that handle rendering and collision boundaries.
class Shape:
def draw(self, screen, position):
pass
def get_bottom_offset(self):
return 0 # Used for collision with the ground
class Circle(Shape):
def __init__(self, radius, color):
self.radius = radius
self.color = color
def draw(self, screen, position):
pygame.draw.circle(screen, self.color, (int(position.x), int(position.y)), self.radius)
def get_bottom_offset(self):
return self.radius
class Rectangle(Shape):
def __init__(self, width, height, color):
self.width = width
self.height = height
self.color = color
def draw(self, screen, position):
rect = pygame.Rect(
int(position.x - self.width / 2),
int(position.y - self.height / 2),
self.width,
self.height
)
pygame.draw.rect(screen, self.color, rect)
def get_bottom_offset(self):
return self.height / 2
We'll create an interactive simulation where users can add new shapes by clicking, and implement basic UI elements like buttons.
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('2D Physics Engine')
clock = pygame.time.Clock()
def main():
objects = []
running = True
while running:
dt = clock.tick(60) / 1000 # Delta time in seconds
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle user interactions here
# Update objects
for obj in objects:
obj.update(dt)
obj.check_ground_collision(HEIGHT)
# Render
screen.fill((255, 255, 255))
for obj in objects:
obj.shape.draw(screen, obj.position)
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
def main():
objects = []
running = True
while running:
dt = clock.tick(60) / 1000 # Delta time in seconds
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
if event.button == 1: # Left click
# Add Circle
circle_shape = Circle(radius=20, color=(255, 0, 0))
obj = PhysicsObject(
mass=1.0,
position=position,
velocity=(0, 0)
)
obj.shape = circle_shape
objects.append(obj)
elif event.button == 3: # Right click
# Add Rectangle
rect_shape = Rectangle(width=40, height=40, color=(0, 0, 255))
obj = PhysicsObject(
mass=2.0,
position=position,
velocity=(0, 0)
)
obj.shape = rect_shape
objects.append(obj)
Let's add a simple UI with buttons to control simulation parameters.
class Button:
def __init__(self, text, position, size, callback):
self.text = text
self.position = position
self.size = size
self.callback = callback
self.font = pygame.font.SysFont('Arial', 20)
self.rect = pygame.Rect(position, size)
def draw(self, screen):
pygame.draw.rect(screen, (200, 200, 200), self.rect)
pygame.draw.rect(screen, (0, 0, 0), self.rect, 2) # Border
text_surf = self.font.render(self.text, True, (0, 0, 0))
text_rect = text_surf.get_rect(center=self.rect.center)
screen.blit(text_surf, text_rect)
def is_clicked(self, mouse_pos):
return self.rect.collidepoint(mouse_pos)
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if self.is_clicked(event.pos):
self.callback()
def main():
objects = []
def clear_objects():
objects.clear()
buttons = [
Button('Clear', (10, 10), (80, 30), clear_objects)
]
running = True
while running:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle button events
for button in buttons:
button.handle_event(event)
# Handle adding objects
elif event.type == pygame.MOUSEBUTTONDOWN:
# Ensure the click isn't on a button
if not any(button.rect.collidepoint(event.pos) for button in buttons):
position = pygame.mouse.get_pos()
# Add objects as before
# Update and render as before
# Draw buttons
for button in buttons:
button.draw(screen)
pygame.display.flip()
pygame.quit()
sys.exit()
Implement friction when objects are on the ground:
def apply_friction(self, dt):
if self.position.y + self.shape.get_bottom_offset() >= HEIGHT:
friction_coefficient = 0.8
friction_force = -self.velocity * friction_coefficient
self.apply_force(friction_force)
Call apply_friction(dt) in the update loop.
Extend PhysicsObject to handle rotation:
class PhysicsObject:
def __init__(self, mass=1.0, position=(0, 0), velocity=(0, 0), angle=0, angular_velocity=0):
# Existing properties
self.angle = angle
self.angular_velocity = angular_velocity
self.torque = 0
self.moment_of_inertia = self.calculate_moment_of_inertia()
def calculate_moment_of_inertia(self):
# Example for a solid circle: I = (1/2) * m * r^2
if isinstance(self.shape, Circle):
return 0.5 * self.mass * self.shape.radius ** 2
# Add calculations for other shapes
return 1
def apply_torque(self, torque):
self.torque += torque
def update(self, dt):
# Update linear motion as before
# Update angular motion
angular_acceleration = self.torque / self.moment_of_inertia
self.angular_velocity += angular_acceleration * dt
self.angle += self.angular_velocity * dt
self.torque = 0 # Reset torque
Modify the draw methods to account for rotation.
Implement a spatial grid or quadtree to optimize collision detection by reducing the number of checks.
Building a fully-featured physics engine is an extensive task. For more advanced physics simulation, consider studying:
Remember, the key to a successful physics engine is:
Feel free to ask for further details on any section, or if you need assistance with specific implementations. Happy coding!