Continuous Integer-Based Physics Simulation
Unlike the iterative approach which steps through time incrementally, a continuous physics simulation models the entire system as mathematical functions of time. This allows us to calculate the exact state at any desired time point without having to simulate all intermediate steps.
Continuous Motion Equations for Integer Physics
For objects under constant acceleration (like gravity), we can use the following equations to determine position at any time t:
// Using integer math with a scaling factor S
// Position as a function of time (constant acceleration)
position_x(t) = initial_x + (initial_velocity_x * t) + (0.5 * acceleration_x * t * t)
position_y(t) = initial_y + (initial_velocity_y * t) + (0.5 * acceleration_y * t * t)
// These are closed-form solutions to the differential equations of motion
Collision Time Calculation
For continuous collision detection, instead of checking at each time step, we solve for the exact time when two objects will collide:
// For two squares moving along straight-line trajectories:
// Time of collision along x-axis
// For squares s1 approaching s2 from left:
// t_collision_x = (s2.x - s1.x - s1.width) / (s1.velocity_x - s2.velocity_x)
// Time of collision along y-axis:
// t_collision_y = (s2.y - s1.y - s1.height) / (s1.velocity_y - s2.velocity_y)
// Actual collision occurs at min(t_collision_x, t_collision_y) if both are positive
Python Implementation of Continuous Physics
import pygame
import sys
from math import sqrt
# Initialize pygame
pygame.init()
# Constants (scaled for integer math)
WIDTH, HEIGHT = 800, 600
SCALE = 1000 # Scale factor for fixed-point arithmetic
GRAVITY = 10 * SCALE // 100 # Gravity scaled
FPS = 60
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
class PhysicsEvent:
def __init__(self, time, type_event, objects_involved):
self.time = time
self.type_event = type_event # "collision", "boundary"
self.objects_involved = objects_involved
class ContinuousSquare:
def __init__(self, x, y, size, color, vel_x=0, vel_y=0):
# All values are scaled integers
self.initial_x = x * SCALE
self.initial_y = y * SCALE
self.size = size * SCALE
self.initial_vel_x = vel_x * SCALE
self.initial_vel_y = vel_y * SCALE
self.color = color
self.acc_y = GRAVITY # Only gravity in y-direction
self.acc_x = 0
# Current state
self.current_t = 0
self.x = self.initial_x
self.y = self.initial_y
self.vel_x = self.initial_vel_x
self.vel_y = self.initial_vel_y
# Collision history (times where velocity changes)
self.events = []
def add_event(self, time, type_event, objects_involved):
# Add a physics event (like collision) to the object's history
self.events.append(PhysicsEvent(time, type_event, objects_involved))
self.events.sort(key=lambda e: e.time) # Keep events sorted by time
def position_at_time(self, t):
"""Calculate position at any time t using the motion equations."""
# Find the most recent event before time t
recent_event = None
for event in self.events:
if event.time <= t:
recent_event = event
else:
break
if recent_event is None:
# No events before t, use initial conditions
elapsed_t = t
start_x = self.initial_x
start_y = self.initial_y
start_vel_x = self.initial_vel_x
start_vel_y = self.initial_vel_y
else:
# Use conditions after most recent event
elapsed_t = t - recent_event.time
# For this example, we'd need to calculate the state after the event
# This would depend on the event type (collision, boundary, etc.)
# For simplicity, we'll use the current state which assumes
# the events have been processed already
start_x = self.x
start_y = self.y
start_vel_x = self.vel_x
start_vel_y = self.vel_y
# Apply motion equations
x = start_x + (start_vel_x * elapsed_t // SCALE)
y = start_y + (start_vel_y * elapsed_t // SCALE) + (self.acc_y * elapsed_t * elapsed_t // (2 * SCALE))
return x, y
def velocity_at_time(self, t):
"""Calculate velocity at any time t."""
# Find the most recent event before time t
recent_event = None
for event in self.events:
if event.time <= t:
recent_event = event
else:
break
if recent_event is None:
# No events before t, use initial conditions
elapsed_t = t
start_vel_x = self.initial_vel_x
start_vel_y = self.initial_vel_y
else:
# Use conditions after most recent event
elapsed_t = t - recent_event.time
start_vel_x = self.vel_x
start_vel_y = self.vel_y
# Apply velocity equations
vel_x = start_vel_x # Constant x-velocity (no acceleration)
vel_y = start_vel_y + (self.acc_y * elapsed_t // SCALE) # Accelerated y-velocity
return vel_x, vel_y
def update_to_time(self, t):
"""Update the object's state to time t."""
self.x, self.y = self.position_at_time(t)
self.vel_x, self.vel_y = self.velocity_at_time(t)
self.current_t = t
def draw(self, screen):
# Convert scaled integers back to pixels for drawing
pygame.draw.rect(screen, self.color,
(self.x // SCALE, self.y // SCALE,
self.size // SCALE, self.size // SCALE))
class ContinuousPhysicsSimulation:
def __init__(self):
self.objects = []
self.current_time = 0
self.events = [] # Global events queue
def add_object(self, obj):
self.objects.append(obj)
def predict_collision_time(self, obj1, obj2):
"""Solve for the time when two objects will collide."""
# We need to solve quadratic equations for each axis:
# For x-axis: Distance = relative_velocity * t
# For y-axis: Distance = relative_velocity * t + 0.5 * relative_acceleration * t^2
# Relative velocities and positions
rel_vel_x = obj1.vel_x - obj2.vel_x
rel_vel_y = obj1.vel_y - obj2.vel_y
rel_acc_y = obj1.acc_y - obj2.acc_y
# Current positions
x1, y1 = obj1.position_at_time(self.current_time)
x2, y2 = obj2.position_at_time(self.current_time)
# For x-axis (linear motion - no acceleration):
# If objects are moving toward each other on x-axis
if rel_vel_x != 0:
if rel_vel_x > 0: # obj1 is moving right faster than obj2
t_collision_x = (x2 - x1 - obj1.size) * SCALE // rel_vel_x
else: # obj1 is moving left faster than obj2
t_collision_x = (x1 - x2 - obj2.size) * SCALE // (-rel_vel_x)
# Check if collision will actually occur (not moving away from each other)
if t_collision_x < 0:
t_collision_x = float('inf')
else:
# No relative x velocity, check if already overlapping
if (x1 < x2 + obj2.size and x1 + obj1.size > x2):
t_collision_x = 0 # Already overlapping
else:
t_collision_x = float('inf') # Will never collide
# For y-axis (motion with acceleration):
# This is more complex due to acceleration
# We need to solve a quadratic equation:
# 0.5 * rel_acc_y * t^2 + rel_vel_y * t + (y1 - y2 - obj1.size) = 0
# Simplified approach:
# We'll iterate through time to find the collision point
# This is not truly continuous but provides a reasonable approximation
t_collision_y = float('inf')
test_time = self.current_time
time_step = SCALE // 10 # Small time step for checking
while test_time < self.current_time + SCALE * 5: # Look ahead 5 seconds
y1_test, y2_test = obj1.position_at_time(test_time)[1], obj2.position_at_time(test_time)[1]
if (y1_test < y2_test + obj2.size and y1_test + obj1.size > y2_test):
t_collision_y = test_time - self.current_time
break
test_time += time_step
# The collision occurs at the minimum positive time
if t_collision_x < t_collision_y and t_collision_x >= 0:
return self.current_time + t_collision_x, "x-axis"
elif t_collision_y >= 0:
return self.current_time + t_collision_y, "y-axis"
else:
return float('inf'), None # No collision
def predict_boundary_collision(self, obj):
"""Predict when an object will hit the screen boundaries."""
# Calculate times for each boundary collision
times = []
# Left boundary
if obj.vel_x < 0:
t_left = -obj.x * SCALE // obj.vel_x
times.append((self.current_time + t_left, "left"))
# Right boundary
if obj.vel_x > 0:
t_right = ((WIDTH * SCALE) - obj.x - obj.size) * SCALE // obj.vel_x
times.append((self.current_time + t_right, "right"))
# Top boundary
if obj.vel_y < 0:
t_top = -obj.y * SCALE // obj.vel_y
times.append((self.current_time + t_top, "top"))
# Bottom boundary - with gravity, this is a quadratic equation
# y(t) = y0 + v0*t + 0.5*a*t^2 = HEIGHT - size
# Solve: 0.5*a*t^2 + v0*t + (y0 - HEIGHT + size) = 0
# Simplified approach using iteration (similar to object collision)
t_bottom = float('inf')
test_time = self.current_time
time_step = SCALE // 10
while test_time < self.current_time + SCALE * 5:
y_test = obj.position_at_time(test_time)[1]
if y_test + obj.size >= HEIGHT * SCALE:
t_bottom = test_time - self.current_time
times.append((self.current_time + t_bottom, "bottom"))
break
test_time += time_step
if times:
return min(times, key=lambda x: x)
else:
return float('inf'), None
def handle_collision(self, obj1, obj2, axis):
"""Handle a collision between two objects."""
# Update velocities based on collision axis
if axis == "x-axis":
# Swap x velocities (elastic collision)
obj1.vel_x, obj2.vel_x = obj2.vel_x, obj1.vel_x
else: # y-axis
# Swap y velocities (elastic collision)
obj1.vel_y, obj2.vel_y = obj2.vel_y, obj1.vel_y
def handle_boundary_collision(self, obj, boundary):
"""Handle a collision with the screen boundary."""
if boundary == "left" or boundary == "right":
obj.vel_x = -obj.vel_x
elif boundary == "top" or boundary == "bottom":
obj.vel_y = -obj.vel_y
def predict_next_event(self):
"""Predict the next event (collision) in the system."""
next_event_time = float('inf')
next_event_type = None
objects_involved = []
# Check object-object collisions
for i, obj1 in enumerate(self.objects):
for j, obj2 in enumerate(self.objects[i+1:], i+1):
collision_time, axis = self.predict_collision_time(obj1, obj2)
if collision_time < next_event_time and collision_time > self.current_time:
next_event_time = collision_time
next_event_type = "collision"
objects_involved = [obj1, obj2, axis]
# Check boundary collisions
for obj in self.objects:
boundary_time, boundary = self.predict_boundary_collision(obj)
if boundary_time < next_event_time and boundary_time > self.current_time:
next_event_time = boundary_time
next_event_type = "boundary"
objects_involved = [obj, boundary]
if next_event_type:
return next_event_time, next_event_type, objects_involved
return None, None, None
def advance_to_event(self):
"""Advance the simulation to the next event."""
event_time, event_type, objects_involved = self.predict_next_event()
if event_time is None:
# No more events, advance by a fixed amount
self.advance_to_time(self.current_time + SCALE)
return False
# Advance to the event time
self.advance_to_time(event_time)
# Handle the event
if event_type == "collision":
obj1, obj2, axis = objects_involved
self.handle_collision(obj1, obj2, axis)
obj1.add_event(event_time, "collision", [obj2, axis])
obj2.add_event(event_time, "collision", [obj1, axis])
elif event_type == "boundary":
obj, boundary = objects_involved
self.handle_boundary_collision(obj, boundary)
obj.add_event(event_time, "boundary", [boundary])
return True
def advance_to_time(self, target_time):
"""Advance the simulation to a specific time."""
if target_time <= self.current_time:
return
for obj in self.objects:
obj.update_to_time(target_time)
self.current_time = target_time
def render(self, screen):
"""Render the current state of the simulation."""
screen.fill(WHITE)
for obj in self.objects:
obj.draw(screen)
# Display current simulation time
font = pygame.font.Font(None, 36)
time_text = font.render(f"Time: {self.current_time/SCALE:.2f}s", True, (0, 0, 0))
screen.blit(time_text, (10, 10))
def main():
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Continuous Physics Simulation")
clock = pygame.time.Clock()
# Create simulation
sim = ContinuousPhysicsSimulation()
# Create two squares
square1 = ContinuousSquare(200, 100, 50, RED, vel_x=3, vel_y=0)
square2 = ContinuousSquare(500, 300, 50, BLUE, vel_x=-2, vel_y=0)
sim.add_object(