FIT CTU

Adam Vesecký

vesecky.adam@gmail.com

Lecture 8

Physics

Architecture of Computer Games

Adam Vesecký

Dynamics

Terms

  • Kinematics - determines motion of objects without reference to forces
  • Dynamics - determines how objects interact under the influence of forces
  • Time - a continuous progress of events, measured in seconds
  • Mass - a scalar quantity measured in kilograms
  • Position - a point or an area occupied by an object
  • Velocity - the rate of change of distance over time
  • Acceleration - the rate of change of velocity over time
  • Force - an action exerted upon a body in order to change its state
Most engines use MKS units (meters, kilograms, seconds) and radians for angles.

Dynamics

Linear Dynamics

  • we ignore all rotational effects
  • position can be described by a position vector
  • velocity:
  • acceleration:
  • net force:
  • Newton's second law:
  • linear momentum:

Angular dynamics

  • angular velocity:
  • angular acceleration:
  • torque: , caused by a force applied to a location
Any physical behavior of the object can be decomposed into the linear motion of the center of mass and the angular motion around the same point

Newton's Laws

Lex I

  • A body will remain at rest or continue to move in a straight line at a constant speed unless acted upon by a force.

Lex II

  • The acceleration of a body is proportional to the resultant force acting on the body and is in the same direction as the resultant force.

Lex III

  • When one body exerts a force on a second body, the second body exerts an equal force with opposite direction on the first body.
In most games, Newton's laws don't apply to trees

Motion

Projectile motion

Slope motion (no friction)

Motion

Mass-Spring Motion

  • Hook's Law:
    •  is the spring constant

Equations of motion

  • finding , given knowledge of
  • vertical motion under the influence of gravity
  • moving with variable acceleration
    • drag force:
    • a simple approximation to air friction (the faster we go, the greater the friction force)
    • how to handle this: derive a function for velocity
    • too difficult - with any change of any force, we would need to modify the simulation code
    • analytical solutions are almost never possible in game physics

Numerical integration

  • Conditions:
    • we know an initial value of the function:
    • we know the derivatives
    • we know the time interval
  • given , the problem is to find
  • we will start at  and take steps in time along the tangent, until we generate an approximation for
  • integration methods provide us with the possibility of an approximation with increasing precision

Integration Methods

Implicit methods

  • make use of quantities from the next time step
  • decrease energy from the system

Explicit methods

  • make use of known quantities at each time step

Semi-implicit methods

  • combination of explicit and implicit methods
  • very stable

Runge-Kutta family

  • Euler methods, midpoint methods, RK4,...

Verlet family

  • Regular Verlet
  • Leapfrog Verlet
  • Velocity Verlet

Euler Integration

Explicit method

Improved method

Implicit method

  • cheap and easy to implement
  • high error and poor stability, depending
    directly on the time step

Verlet integration

  • used in molecural dynamics, useful in simulating small particles (cloth, rope, soft objects)
  • time invariant - we can run it forwards and then backwards, ending up in the same place

Regular Verlet

  • derived by adding two Taylor series expansions

Verlet leap-frog

  • method that tracks velocity, but at half a time step off from the position calculation

Velocity Verlet

  • most accurate, acceleration needs to be computed twice
  • advantages over Euler when dealing with multiple bodies

Dynamics in games

Steering Behaviors

Steering Behaviors

  • set of algorithms and principles that help autonomous agents move in a realistic manner by using simple forces
  • designed by Crag Reynolds in the early 90's
  • Agent - a system situated within an envirnoment, with an ability to sense that environment
  • Motion layers
    • action selection - choosing goals, strategy
    • steering - trajectory calculation
    • locomotion - way of moving, animation, articulation

Steering Behaviors

Seek

  • the simplest steering behavior
  • a force that directs an agent toward a target position

Steering Behaviors

Flee

  • opposite of seek
  • creates a force that steers the agent away

Arrive

  • seek + stopping movement
  • decelerates the agent onto the target position, based on given slowing radius

Steering Behaviors

Pursuit

  • agent intercepts a moving target
  • predicts where the target is going to be in the future
  • calls for a good prediction function

Evade

  • opposite of pursuit
  • the evader flees from the estimated future position

Steering Behaviors

Wander

  • produces a force that will give an impression of a random walking
  • small random displacement is applied to the velocity vector every frame
  • a circle is projected in front of the vehicle
  • the vehicle is steered toward a target that moves along the perimeter
  • parameters: circle radius, distance from the vehicle and jittering (randomness)

Steering Behaviors

Path follow

  • moves a vehicle along a set of waypoints
  • the last waypoint can be reached using arrive, the others via seek
  • smooth movement can be achieved using a tolerance radius or Bézier curve approximation
  • very sensitive to configuration (max force, max velocity, radius,...)

Steering Behaviors

Obstacle avoidance

  • steers a vehicle to avoid obstacles (usually approximated by a circle)
  • vehicle has a detection box - rectangular area
  • two forces are calculated: lateral force and braking force

Offset pursuit

  • keeps a vehicle positioned at a specified offset from a leader vehicle
  • useful for battle formations

Steering Behaviors

Flocking

  • combination of three aspects:
    • separation - steers a vehicle away from its neighborhood
    • alignment - keeps the vehicle's direction aligned with its neighbors
    • cohesion - moves a vehicle toward the center of mass of its neighbors

Physics Engine

Physics engine

  • system that approximates physical phenomena in real-time
  • computes dynamics of objects in virtual scene
  • you have to understand your game before you decide how to add a physical simulation to it
  • can improve immersion
  • can support new gameplay events
  • can broke the game story
  • can take up significant computing resources

Physics Engines

N-Collide

  • 2D/3D collision detection library written in Rust

Box2D

  • open-source C++ 2D physics engine
  • supports CCD (continuous collision detection)

Bullet

  • open-source 3D physics engine
  • used in game and film industry
  • supports CCD

PhysX

  • NVidia GPU engine
  • PhysX destruction, PhysX clothing, PhysX particles

p2.js

  • module JavaScript engine, supports CCD

Havok

  • gold commercial standard

Physics engine flow

Physics and animation

  • physics  animation!
  • animations must cooperate with physics engine to run seamlessly
  • cut-scenes and state-transition animations are detached from physics
  • physics-based interactions - animations generated by physics engine
    • better results, but more difficult to implement

Physics engine features

  • collision detection
  • contact callbacks
  • joints
  • concave and convex hulls
  • compound bodies
  • sleeping objects
  • raycasting, shapecasting
  • deformable structures
  • destructible structures
  • trigger volumes
  • complex machines
  • drivable vehicles
  • rag doll characters
  • water surface, hair, cloth
  • particles

Physics in games

Pinballs (1980+)

  • non-trivial OBB collision detection

The Incredible Machine (1993)

  • advanced physical interactions

Half-Life 2 (2004)

  • destructible environment, liquid physics

Angry Birds (2009)

  • physics as the core mechanic

INSIDE (2016)

  • soft-bodies driven by a network of impulses

Half-Life Alyx (2020)

  • physics-based interactions

Noita (2020)

  • pixel-level physics simulation

Object types

Body

  • fundamental object in the physics scene

Rigid Body

  • idealized, infinitely hard, non-deformable solid object
  • physics-driven bodies - driven entirely by the simulation
  • game-driven bodies - moved in a non-physical way (animations)
  • fixed bodies - collision-only bodies (e.g. triggers)

Soft body

  • deformable

Shape

  • region of space described by a boundary, with a definite inside and outside (curved line, polygon, curved surface, polyhedron)

Fixture

  • used to describe size, shape and material properties

Object Types

Constraint

  • connects bodies together in order to simulate interaction (ropes, wheels, vehicles, chains)

Sensor/Phantom

  • entity that provides a feedback when certain objects overlap
  • participates on collision detection but doesn't affect the scene

Rag doll

  • displays human-like figures with a realistic motion

Destructible object

  • breakable object, can be implemented by using rigid body dynamics, dividing the model into a number of breakable pieces

Constraints

  • Revolute - a hinge or pin, where the bodies rotate
    • wheels, chains, rotating doors, catapults, levers
  • Distance - a point on each body will be kept at a fixed distance apart
  • Rope - restricts the maximum distance between two points
  • Prismatic - body's motion is restricted to a single degree of freedom
    • elevators, sliding doors, pistons
  • Weld - holds the bodies at the same orientation
  • Cone-Twist - adds a cone and twist axis limits (6 degrees of freedom)
  • Gear - controls two other joints so that the movement of one affects the other
  • Motor - joint with torque or angular impulses

Constraints

rope

revolute

prismatic

cone-twist

Constraints

Fracturing

  • breaking an object into smaller fragments
  • in many cases destruction is not dynamic (can be made using animations)
  • techniques: manual fracturing, boolean operations, voxels, Voronoi Shattering

Soft bodies and liquids

  • usually implemented as a combination of particle systems and visual effects
  • common model:
    1. apply collision detection upon particles
    2. apply pressure and repulsive forces
    3. update positions
    4. handle interaction with other objects

Particle Systems

  • a collection of point masses that obeys certain physical laws
  • can model complex fuzzy shapes and dynamics
  • uses Flyweight pattern (array of positions, velocities, group lists)
  • particles are not only moving points! Even a tree may become a particle

Applications

  • fluids
  • visual effects
  • flocks
  • rendered trails (plants)
  • soft bodies (flag, cloth)

Basic model

  1. generate new particles
  2. assign individual attributes
  3. extinguish dead particles
  4. move and transform particles according to their dynamic values
  5. render meshes

Collision Detection

Collision Detection

Steps

  • positions for the next frame are determined
  • a spatial data structure finds collision candidates
  • collision candidates are filtered out into a set of real collision pairs
  • collisions are resolved by the collision resolver, by applying impulses or penalty forces
  • constraints are satisfied by the constraint resolver

Collidable entities

  • we need to provide a collision representation for each object
  • simple shapes are preferred (a car might be modelled as a rectangle)
  • more-complex shapes should only be used when the simples ones provide inadequate information to achieve the desired behavior
  • if collidable entities don't overlap, no more testing is required
  • if they do overlap, more refined testing is required

Example: Unity Interaction Matrix

Static ColliderRigidbody ColliderKinematic Rigidbody ColliderStatic Trigger ColliderRigidbody Trigger ColliderKinematic Rigidbody Trigger Collider
Static Collidercollisiontriggertrigger
Rigidbody Collidercollisioncollisioncollisiontriggertriggertrigger
Kinematic Rigidbody Collidercollisiontriggertriggertrigger
Static Trigger Collidertriggertriggertriggertrigger
Rigidbody Trigger Collidertriggertriggertriggertriggertriggertrigger
Kinematic Rigidbody Trigger Collidertriggertriggertriggertriggertriggertrigger

Primitives

Sphere

  • center point and radius (4 numbers for 3D)

Capsule

  • 2D: rectangle and two circles
  • 3D: cylinder and two hemispherical end-caps
  • representation: two points and radius

AABB

  • axis-aligned bounding box
  • rectangular volume (cuboid) whose faces are parallel to the axes of the coordinate system
  • very efficient test for penetration
  • AABB must be recalculated whenever the object rotates

Primitives

OBB

  • oriented bounding box
  • defined by a position, half-extents and orientation
  • commonly used

k-DOP

  • discrete oriented polytope
  • more general case of AABB and OBB
  • approximates the shape of an object

Convex volume

  • more general shape
  • must be convex
  • expensive for intersection test

Primitives

Poly Soup

  • used to model complex static geometry (terrain)
  • very expensive kind of collision test

Compound shapes

  • more efficient alternative to a poly-soup
  • the system first tests bounding volumes of compound shapes

Convex hull

  • smallest convex volume containing the object

Complex shape/volume

  • not necessarily convex
  • simplified mesh/sprite
  • needs preprocessing (BSP)

Comparison

Collisions in 2D games

  • even side-scrollers need compound objects
  • simple AABB collision will not work for irregular sprites

Looking for collision candidates

Naive solution

  • each pair
  •  -> 10 objects result in 100 checks, 100 in 10 000 etc.

Quad-tree

  • efficiency is , since the index takes about  comparisons to traverse
  • good for point-like small objects
  • worst case:

Sweep and Prune

  • sorts the starts (lower bounds) and ends (upper bound) of bounding volumes of each solid along a number of axes

BSP

  • binary space partitioning, good for complex static geometries (buildings)

Grid, Oct-tree, R-tree, R+tree, R*tree, X-tree, M-tree,...

Resolving collision candidates

Sphere-Sphere

  • , where  is a central point

Sphere-ray

  • we just test the distance between a single sphere center and a ray

AABB-AABB

  • test the borders

AABB-Ray

  • intervals  and  mustn't overlap

Resolving collision candidates

Capsules

  • capsule-capsule - calculate the distance between two line segments
  • capsule-ray - find the distance between a ray and a line segment

OBB-OBB

  • axis-separating theorem by Gottschalk

Triangles

  • triangle-triangle - compute the plane equation and test each point if it lies on the same side
  • triangle-ray - Möller's affine combination

SAT

SAT (separating axis theorem)

  • based on collection of intersection tests
  • if an axis can be found along which the projection of two convex shapes do not overlap, then the two shapes do not intersect
  • for 2D: AABB 2 axes, OBB 4 axes
  • for 3D: AABB 3 axes, OBB 15 axes

Other methods

  • GJK, Line Sweep, Sphere test

SAT Example

  • AABB in 2D: only 2 axis to test

Tunneling problem

Stepped world

  • time steps vary based on occurring situation
  • collision time is calculated by doing binary search in time, moving object back and forth by 1/2 steps (5 iterations is usually enough)

Continuous Collision Detection (CCD)

  • uses Swept Shapes technique
  • a new shape is formed by the motion of the original one
  • rotating shapes may result in shapes that aren't convex

Collision queries

Queries:

  • find the first target the bullet hits
  • can the camera move without interpenetrating the wall?
  • find all objects within a given radius

Ray casting

  • any game is going to need a good raycaster
  • the cast line segment is tested against the collidable objects in the collision world; if it intersects any of them, the contact point is returned
  • weapon systems, player mechanics, AI systems, vehicle systems, line-of-sight
  • in addition, used in 80's and 90's for pseudo-3D rendering, nowadays is being replaced by raytracing

Shape casting

  • how far a shape would be able to travel along a directed line segment before it hits something
  • sphere casts - e.g. to determine whether the camera is in a collision
  • capsule casts - e.g. character movement on uneven terrain

Collision response

How to respond to a collision?

Explosion

  • adding energy to a system of rigid bodies

Fracturing

  • breaking objects apart

Restitution

  • amount of bounce an object has when it hits something

Impulsive response

  • when two bodies collide, they compress slightly and then rebound, changing their velocities, losing energy

Friction

  • force that arises between two bodies that are in continuous contact, resisting their movement relative to one another
  • removes energy from a system of rigid bodies
  • static, dynamic, rolling

Collision Resolver

Collision Resolving

  • LCP - Linear Complementarity Problem
  • very complex numeric algorithms
  • resolvers: PGS, Dantzig solver, Lemke method, Jacobi method

Coming to rest

  • all objects lose energy, leading to eventual rest
  • not simple (floating-point error, inaccuracies, numerical instability)
    • sleep criteria
      • momentum or energy are below a threshold
    • simulation islands
      • grouping objects that either are interacting or have a potential to interact

Common issue of simple resolvers

Sleeping Objects

Lecture Summary

  • I know basic motion equations
  • I know basic Euler integration methods
  • I know basic types of steering behaviors
  • I know object types for physics engines
  • I know basic constraints, such as rope, revolute, prismatic, and cone-twist
  • I know basic collision primitives
  • I know SAT theorem
  • I know what CCD is
  • I know what particle systems are