Cse 381 advanced game programming collision detection
1 / 75

CSE 381 Advanced Game Programming Collision Detection - PowerPoint PPT Presentation

  • Uploaded on

CSE 381 – Advanced Game Programming Collision Detection. Remember This?. We spent a lot of time on this in the spring Remember what we learned What will we add? Sweep and Prune algorithm (today) GJK algorithm (Monday). What is collision detection?.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'CSE 381 Advanced Game Programming Collision Detection' - Mia_John

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Remember this
Remember This?

  • We spent a lot of time on this in the spring

  • Remember what we learned

  • What will we add?

    • Sweep and Prune algorithm (today)

    • GJK algorithm (Monday)

What is collision detection
What is collision detection?

  • Determining if, when, & where two objects intersect

  • What objects?

    • Linear components, planes, triangles, rectangles, oriented boxes, spheres, capsules, lozenges, cylinders, ellipsoids, etc.

  • Hugely important part of a 3D game engine. Why?

    • done continuously every frame

    • involves huge amounts of computations

  • Entire textbooks are written on this subject alone

    • Real-Time Collision Detection by Christer Ericson

    • Collision Detection in Interactive 3D Environments by Gino van den Bergen

For what is collision detection used
For what is collision detection used?

  • In 3D gaming:

    • prevent players/monsters from walking through walls

    • prevent players/monsters from walking/falling through terrain

    • react to players/monsters colliding with each other

    • react to players/monsters colliding with game objects

      • i.e., pick up ammo

    • react to projectiles colliding with players/monsters

      • i.e., take health away for being hit by a bullet

    • ragdoll physics

Why so important
Why so important?

  • Because if done improperly, it can ruin a game

    • collision detection problems can still be found in state of the art games

      • Ever get stuck in a wall?

      • Ever go behind a wall you’re not supposed to?

      • Ever have a collision that doesn’t look like a collision?

  • Because if done inefficiently, it will ruin gameplay

Collision detection graphics
Collision Detection & Graphics

  • Work together in a game engine

  • Should be developed together

  • Both share:

    • geometric data

    • timing elements

  • So, pool resources for their algorithms

    • e.g., scene graphs, spatial partitioning (octrees, bsps…)

Game engine collision detection
Game Engine Collision Detection

  • 2 phases

    • Broad phase: determine which pairs of shapes need to be tested for collision

    • Narrow phase: determine collision results for each pair identified in broad phase

  • All game objects maintain collision sets

    • data for collisions calculations

    • i.e., bounding volumes

Types of collisions
Types of Collisions

  • Object versus plane (navigation or culling)

  • Object versus object (general collision)

  • Linear component versus object (picking)

Imagine a complex world
Imagine a complex world

  • Hundreds of interior structures, each with rooms

  • Complex external terrain environment

  • Water with underwater structures (interiors)

  • Rather than testing these items serially, we can do so hierarchically

    • much faster

    • continuously reduce the problem

How should collision data be organized
How should collision data be organized?

  • One of the most important questions in designing a collision system

  • Game world might contain a large number of interacting objects

    • an exhaustive comparison is too exhaustive

  • Objects should be organized into collision groups

    • e.g., rooms, partitions, etc.

Rooms as collision groups
Rooms as collision groups

  • Scene graphs & collision sets are not static, they change with the game

    • as players, NPCs, or other game objects move/change

  • When a player enters a room, the scene graph is reconfigured

    • player is now part of room collision group

  • Only objects moving within a room are tested against one another for collisions

Collision detection game physics
Collision Detection Game Physics

  • This is a huge topic

  • Game physics is rapidly changing

Collision detection response
Collision Detection & Response

  • Collision Detection

    • detecting what game objects are colliding with each other

  • Collision Response

    • providing a programmed response to collisions that fits with the game’s design & custom laws of physics

Static vs dynamic objects
Static vs. Dynamic Objects

  • Static objects never move

  • Dynamic objects move

  • Collisions may be between:

    • Static objects & dynamic objects (fast & easy)

    • Dynamic objects & dynamic objects (harder)

What types of collisions might we care about
What types of collisions might we care about?

  • Main character and static objects:

    • terrain, floor, tiles, walls, furniture, buildings, game objects (i.e. power-ups, ammo), etc.

  • Main character & dynamic objects:

    • enemies, projectiles (i.e. bullets, arrows, etc.), particles (expensive), etc.

  • Other dynamic objects and:

    • other static objects

    • other dynamic objects

Collisions in pairs
Collisions in Pairs

  • In collision detection, we always compare pairs of objects. Easier to:

    • understand

    • design & implement solutions

  • A naïve approach:

    • one pair at a time, compare all game objects in a game world against all other game objects in a game world

Collision detection calculations
Collision Detection Calculations

  • What data are we looking for?

    • Do these two objects potentially collide?

    • Do these two objects collide?

    • When did these two objects collide?

    • Where did these two objects collide?

      • where on geometry of objects, points of impact

  • These 4 questions get progressively:

    • more computationally expensive to implement

    • more complex to implement (more math)

Phases of collision detection
Phases of Collision Detection

  • Spatial Partitioning Algorithms

    • problem reduction

    • only perform additional phases on pairs of object on same “islands”

  • Broad Phase – early rejection tests

    • Do the coarse Bounding Volumes of two objects collide?

  • Narrow Phase

    • What are the contact points on object geometries?

      • Done down to the last triangle in 3D games

Bounding volumes
Bounding Volumes

  • The base geometry used for all collision tests

    • instead of the shape’s geometry, which is too expensive

  • Properties of desirable BVs:

    • inexpensive intersection tests

    • tight fitting

    • inexpensive to compute

    • easy to rotate and transform

    • use little memory

  • Ref: [1]

Assumptions you might make
Assumptions you might make

  • All collideable game objects:

    • have rectangular Bounding Volumes

    • don’t rotate, or

    • if they do rotate, we don’t care about them colliding with stuff

  • Thus:

    • no polytope collision detection equations

    • no rotation equations

    • this makes life much easier (no narrow phase)

Common bounding volumes
Common Bounding Volumes

  • Note that the space craft has been rotated

  • Ref: [1], Figure 4.2

  • This semester, we like AABBs and/or Spheres

    • axis-aligned bounding boxes

How about a big complicated object
How about a big, complicated object?

  • We can have 2 AABBs

    • Don’t test them against each other

Spatial partitioning
Spatial Partitioning

  • First, reduce the problem

  • only perform additional phases on pairs of object on same “islands”

  • Common Solutions:

    • Octree Algorithms (quadtrees for 2D)

    • also: Portals (ala Quake), BSP trees (Binary Space Partitions), Spatial Hashing, etc.

  • Octrees

    • Used to divide a 3D world into “islands”

      • 2D divided via Quadtrees

    • Why?

      • to make rendering more efficient

      • to make collision detection more efficient

    • What would be the data for these nodes?

      • region coordinates for cell

        • though a smart implementation might eliminate this too

      • AABBs


    • Source: http://en.wikipedia.org/wiki/Image:Octree2.png

    Octree drawbacks
    Octree Drawbacks

    • Objects cross islands

      • octree has to be constantly updated

      • not so bad

    • Objects straddle islands

      • collision detection may involve objects from multiple islands

      • can be a headache

    Uniform grids
    Uniform Grids

    • Fast mechanism for reducing the problem

      • used for 2D & 3D games

    • Steps:

      • divide the world into a grid of equal sized cells

      • associate each object with the cells it overlaps

      • only objects sharing a cell are compared

    • Serves 2 purposes:

      • reduces the problem for object-object collision detection

      • provides solution for easy object-terrain collision detection

    Calculating grid position
    Calculating Grid Position

    • What cells does our object currently occupy?

    • How would you calculate that?

      • For min/max tile rows/columns:

        • object.X/terrainCellW

        • object.Z/terrainCellL

        • (object.X+aabb.Width)/terrainCellW

        • (object.Z+aabb.Height)/terrainCellL

      • For this guy, cells (0,y,0), (0,y,1), (1,y,0), & (1,y,1)

        • only test against:

          • other objects in those cells

          • collidable tiles in those cells (treat like objects)

            • don’t let sprites occupy “collidable cells”

    Grid cell collision walkable surfaces
    Grid Cell Collision & Walkable Surfaces

    • Side-scrollers simulate gravity

      • not necessarily accelerated (constant velocity)

      • move all affected sprites down by dY

    • This way, characters can fall

    • We must detect when sprites are colliding with a floor/platform

    • Easy solution: make a tile with a walkable surface at the very top of the image

    • Collision system will handle response

    Grid cell collision advantages disadvantages
    Grid Cell Collision Advantages/Disadvantages

    • Advantages

      • easy to implement

      • very fast (computationally inexpensive)

    • Only good for certain types of predicatable collisions

      • Physics simulations require more complex approaches


    • Spatial Partitioning

      • Octrees

      • Portals, BSPs, etc.

      • Uniform Grids

    • What purpose do they serve?

      • reduce the problem of collision detection

      • How?

        • reduce the number of object-object tests

    Object tests premise
    Object Tests Premise

    • Think of all collision tests as between pairs of collidable objects

    • In our games this means:

      • object – to – object

    • In a single game loop, for each object, we may have to check against

      • other moving objects (tricky)

      • other stationary objects (easier)

    Broad phase
    Broad Phase

    • Do the coarse AABBs of two objects collide?

    • Common solution:

      • separating axis algorithms

      • including temporal coherence

    • For efficiencies use:

      • Sweep & Prune

      • an extension of separating axis, more efficient for many elements

    Narrow phase
    Narrow Phase

    • What are the contact points on object geometries?

      • for 3D might be convex hulls

    • Two Steps

      • determine potentially colliding primitives (ex: triangles) of a pair of objects

        • AABB tree algorithms

      • determine contact between primitives

        • GJK algorithms

    • Ref[3]

    Position calculations
    Position Calculations

    • New Position with constant velocity:

      xt = x0 + (vx * t)

      yt = y0 + (vy * t)

      zt = z0 + (vz * t)

    • Velocity is a Vector, (vx, vy, vz), or (vx, vy) in 2D

    • Example, object at (1, 5), velocity of (4, -3)

    Velocity vectors
    Velocity Vectors

    • Velocities have direction, their vector

      Vtotal = √(Vx2 + Vy2 + Vz2) for 3D games

      Vtotal = √(Vx2 + Vy2) for 2D games


    • Rate of change of velocity

    • New Velocity (vt) with Acceleration:

      vt = dx/dt = v0 + (a * dt)

    • NOTE – each of these calculations are in one dimension

      • You would perform similar calculations on y & z axes

    • NOTE: we will avoid mid-frame acceleration

      • everybody does it, so will we

    Trajectory assumption
    Trajectory Assumption

    • In a single frame, if no force is exerted upon an object, it will have a constant velocity for that frame

    Forces and vectors
    Forces and vectors

    • F = ma

    • Collisions produce forces on both colliding objects

    • Forces have direction, their vector

      • Forces in x, y, & z axes

    • Ftotal = √(Fx2 + Fy2 + Fz2) for 3D games

    • Ftotal = √(Fx2 + Fy2) for 2D games

    Forces can be summed
    Forces can be summed

    • Done axis by axis

      Fx = F1x + F2x + F3x

      Fy = F1y + F2y + F3y

      Fz = F1z + F2z + F3z


    • (P) – A property that objects in motion have

      P = m * v, measured in kg * m/s

    • Force equation can be reduced to:

      F = dP/dt

    Momentum collisions
    Momentum & Collisions

    • Note: Ignore friction for now

    • Momentum transfer – if 2 objects collide:

      • A perfectly elastic collision: no loss of energy

        • Momentum is conserved

      • An imperfect elastic collision: some energy is converted into heat, work, & deformation of objects

        • Momentum is reduced after collision

    Rigid bodies
    Rigid Bodies

    • Note: we are only dealing with rigid bodies

    • No deformation due to collisions

    Calculating new velocities
    Calculating new velocities

    • Note:

      • ignore rotation/angular velocities for now

      • ignore centers of mass for now

    • 2 moving blocks collide:

      • Block A: mA & vAi

      • Block B: mB & vBi

    • Question, if they collide, what should their velocities be immediately after the collision?

      • vAf & vBf

    Why are we interested in final velocities
    Why are we interested in final velocities?

    • When a collision precisely happens, we want to:

      • move our objects to that precise location

      • change their velocities accordingly

    Calculating v af v bf
    Calculating vAf & vBf

    • If momentum is conserved after collision:

      PAi + PBi = PAf + PBf

      (mA * vAi) + (mB * vBi) = (mA * vAf) + (mB * vBf)

    • Problem has 2 unknowns (vaf & vbf)

      • we need a second equation (Kinetic energy equation)

      • ke = (m * v2)/2, where ke is never negative Joules (J)

      • insert the ke equation into our momentum equation

        vAf = ((2 * mB * vBi) + vAi * (mA – mB))/(mA + mB)

        vBf = ((2 * mA * vAi) – vBi * (mA – mB))/(mA + mB)


    • 2 blocks moving

    • Block A:

      • mass is 10, initial velocity is (4, 0)

    • Block b:

      • mass is 10, initial velocity is (-4, 1)

    • Results:

      • Block A final velocity is (-4, 1)

      • Block B final velocity is (4, 0)

    • See my ElasticCollisionsVelocityCalculator.xls

    Continuous collision detection
    Continuous Collision Detection

    • For each moving object, compute what grid cells it occupies and will cross & occupy if its current velocity is added

    • Find the first contact time between each object pair

    • Sort the collisions, earliest first

    • Move all affected objects to time of first collision, updating positions

    • Update velocities of collided objects

    • Go back to 1 for collided objects only

    • If no more collisions, update all objects to end of frame

    • Ref[3]

    Time in between frames
    Time in between frames

    • We will make calculations and update velocities and positions at various times

    • When?

    • In response to:

      • input at start of frame

      • AI at start of frame

      • collisions/physics when they happen

        • likely to be mid-frame

    Axis separation tests
    Axis Separation Tests

    • How do we know if two AABBs are colliding?

      • if we can squeeze a plane in between them

      • i.e. if their projections overlap on all axes







    Be careful of tunneling
    Be careful of Tunneling

    • What’s that?

    • An object moves through another object because collision is never detected

    A note about timing
    A note about timing

    • If we are running at 30 fps, we are only rendering 1/30th of the physical states of objects

      • Squirrel Eiserloh calls this Flipbook syndrome [2]

    • More things happen that we don’t see than we do

    • We likely won’t see the ball in contact with the ground

    One way to avoid tunneling
    One way to avoid tunneling

    • Swept shapes

    • Potential problem: false positives

      • Good really only for early rejection tests

    Better way to avoid tunneling
    Better way to avoid tunneling

    • Calculate first contact times

    • Resolve contacts in order of occurrence

    Times as
    Times as %

    • You might want to think of your times as % of the frame

    • Then correct positions according to this %

    • For example, if I know my object is supposed to move 10 units this frame (we’ve locked the frame rate), if a collision happens ½ way through, move all affected objects ½ distance of their velocity and recompute collisions data for collided data

    • Re-sort collisions and find next contact time

    % Example

    • A at (1, 5,0), velocity of (4, -3,0)

    • B stationary at (4, 4,0)

    • When will they collide?

      • When A goes one unit to the right

      • How long will that take?

      • If it takes 1 frame to go 4 units, it will take .25 frames to go 1

    (0, 0, 0)

    + x

    + y

    What about 2 moving objects
    What about 2 moving objects?

    • Solution, give the velocity of one to the other for your calculations

      • make one of them stationary

      • then do the calculation as with grid tiles

      • make sure you move both objects

      • make sure you update the velocities of both objects

    So how do we calculate the when
    So how do we calculate the when?

    • We can do it axis by axis

      • What’s the first time where there is overlap on all 3 axes?

    • For each axis during a frame, what is the time of first and last contact?

    • Time of first contact is

    Again for 2 moving bodies freeze one
    Again, for 2 moving bodies, freeze one

    • Object A

      • (xA, yA, zA, vxA, vyA, vzA)

    • Object B

      • (xB, yB, zB, vxB, vyB, vzB)

    • Give velocity of B to A, now A is:

      • (xA, yA, zA, vxA-vxB, vyA-vyB, vzA-vzB)

    First time of contact
    First time of contact

    • For object A, in x-axis

      • (xA, yA, zA, vxA-vxB, vyA-vyB, vzA-vzB)

      • Time = distance/velocity

      • Since velocity = distance/time

        if ((xB-(Bwidth/2)) > (xA+(Awidth/2)))


        tx_first_contact = (xB-(Bwidth/2) – (xA + (Awidth/2)))/(vxA-vxB);

        tx_last_contact = ((xB + (Bwidth/2)) – (xA-(Awidth/2)))/vxA-vxB);

        if (tx_first_contact > 1) no collision


    What if ((xB-(Bwidth/2)) < (xA+(Awidth/2)))?

    Time calculation example
    Time Calculation Example

    • Awidth = 2, Bwidth = 2

    • A at (1, 1, 0), velocity of (4, 3, 0)

    • B at (4, 2, 0), velocity of (-1, 0, 0)

    • When will they start colliding on x-axis?

      • if ((xB-(Bwidth/2)) > (xA+(Awidth/2)))

      • {

      • tx_first_contact = (xB-(Bwidth/2) – (xA + (Awidth/2)))/(vxA-vxB);

      • tx_last_contact = ((xB + (Bwidth/2)) – (xA-(Awidth/2)))/vxA-vxB);

      • if (first_contact > 1) no collision

      • }

    (0, 0, 0)

    tx_first_contact = 1/5 t

    tx_last_contact = 1t

    Physics timing
    Physics & Timing

    • Christer Ericson & Erin Catto’s recommendations:

      • physics frame rate should be higher resolution than rendering

      • minimum of 60 frames/second for physics calculations

      • makes for more precise, and so realistic interactions

    • How do we manage this?

      • tie frame rate to 60 fps, but don’t render every frame

      • don’t worry about this for now

    • Note: these operations might commonly be done in different threads anyway (have their own frame rates)

    Sweep prune
    Sweep & Prune

    • Also called Sort & Sweep

    • A broad phase algorithm

    • This is an efficient way of managing data for method of separating axis (MSA) tests

    • Baraff, D. (1992), Dynamic Simulation of Non-Penetrating Rigid Bodies, (Ph. D thesis), Computer Science Department, Cornell University

    Improvements on msa
    Improvements on MSA

    • It greatly reduces the number of object-object comparisons.

    • How?

      • it only compares objects near each other on one of the 3 axes

    • How?

      • sorting

    Sweep prune approach
    Sweep & Prune approach

    • Think of each axis separately, for each object considered:

    • Calculate position range on x-axis

      • extract (minX, maxX)

    • Place all (minX, maxX) pairs into array

    • Sort array by minX

      • now, it’s easy to see what overlaps in X axis

      • an O(N) problem, not O(N2). Why?

        • don’t compare all objects to one another, only ones “near” each other

      • note, we’ll have sorting costs, of course

    • For x-axis collided pairs, repeat for Y & Z axes

    • Pairs that overlapped on all 3 tests collided

    Combining our algorithms
    Combining our Algorithms

    • Sweep and Prune will tell us if a collision might happen

    • Continuous collision detection will tell us when it happens

      • it might also tell us S & P gave us a false positive


    • Selecting a 3D object from its 2D projection on the screen by pointing and clicking with a mouse

    • Why is this useful?

      • players selecting game objects/targets

        • i.e., which enemy to attack

      • bullets traveling through game world

        • determining which player/NPC it hits

    How is picking done
    How is picking done?

    • Build a ray (like a vector)

      • Where’s the origin?

        • the camera

        • a gun

      • What direction is the ray?

        • from camera to a world point that projects onto the screen at the screen location

    • Find those objects that are intersected by the ray

    Testing for picking intersections
    Testing for picking intersections

    • Traverse through scene graphs to find those with triangles that intersect the ray

    • Gather data about these intersections as needed

      • Point of intersection

      • Normal vector at intersection

      • Surface attributes (color, texture coordinate)

      • Etc.

    • Find the closest triangle to the ray’s origin

    How do we test intersections with linear components
    How do we test intersections with linear components?

    • Depends on what it’s intersecting

      • sphere

      • box

      • triangle

    • Each use different types of calculations

      • e.g., sphere collision equations based on use of quadratic equation

    Recursively finding triangles pseudocode
    Recursively finding triangles pseudocode

    void FindPickTriangles(Node node, Ray ray, PickResults results)


    if (ray intersects node.boundingVolume)


    if (node is a leaf)


    for each triangle of node do


    if (ray intersects triangle)

    add intersection information to results;





    for each child of node do

    DoPick(child, ray, results);




    Scene graphs picking
    Scene Graphs & Picking

    • What’s a node?

      • represents a visual object in the game

      • has a bounding volume

      • may have child nodes

    • If a ray intersects a node, it may intersect a child of that node

    • If a ray does not intersect a node, it will not intersect any of its child nodes

    • So what?

      • this will greatly reduce the problem at hand


    • [1] Real Time Collision Detection by Christer Ericson

    • [2] Physics for Game Programmers by Squirrel Eiserloh

    • [3] Collision Detection in Interactive 3D Environments by Gino van den Bergen


    • [1] Real Time Collision Detection by Christer Ericson

    • [2] Physics for Game Programmers by Squirrel Eiserloh

    • [3] Collision Detection in Interactive 3D Environments by Gino van den Bergen


    • Advanced Collision Detection Techniques

      • http://www.gamasutra.com/features/20000330/bobic_01.htm

    • N-Tutorials: Collision Detection & Response

      • http://www.harveycartel.org/metanet/tutorials/tutorialA.html

    • Physics in BSP Trees: Collision Detection

      • http://www.devmaster.net/articles/bsp-trees-physics/

    • 3D Game Engine Design by David H Eberly