CSE 381 – Advanced Game Programming Collision Detection.

75
CSE 381 – Advanced Game Programming Collision Detection

Transcript of CSE 381 – Advanced Game Programming Collision Detection.

Page 1: CSE 381 – Advanced Game Programming Collision Detection.

CSE 381 – Advanced Game ProgrammingCollision Detection

Page 2: 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)

Page 3: CSE 381 – Advanced Game Programming 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

Page 4: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 5: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 6: CSE 381 – Advanced Game Programming Collision Detection.

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…)

Page 7: CSE 381 – Advanced Game Programming 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

Page 8: CSE 381 – Advanced Game Programming Collision Detection.

Types of Collisions

• Object versus plane (navigation or culling)

• Object versus object (general collision)

• Linear component versus object (picking)

Page 9: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 10: CSE 381 – Advanced Game Programming Collision Detection.

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.

Page 11: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 12: CSE 381 – Advanced Game Programming Collision Detection.

Collision Detection Game Physics

• This is a huge topic

• Game physics is rapidly changing

Page 13: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 14: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 15: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 16: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 17: CSE 381 – Advanced Game Programming Collision Detection.

Collision Detection Calculations

• What data are we looking for?1. Do these two objects potentially collide?

2. Do these two objects collide?

3. When did these two objects collide?

4. 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)

Page 18: CSE 381 – Advanced Game Programming 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

Page 19: CSE 381 – Advanced Game Programming Collision Detection.

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]

Page 20: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 21: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 22: CSE 381 – Advanced Game Programming Collision Detection.

How about a big, complicated object?

• We can have 2 AABBs– Don’t test them against each other

Page 23: CSE 381 – Advanced Game Programming Collision Detection.

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.

Page 24: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 25: CSE 381 – Advanced Game Programming Collision Detection.

Octree

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

Page 26: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 27: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 28: CSE 381 – Advanced Game Programming Collision Detection.

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”

Page 29: CSE 381 – Advanced Game Programming Collision Detection.

• 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 & Walkable Surfaces

Page 30: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 31: CSE 381 – Advanced Game Programming Collision Detection.

Again

• 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

Page 32: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 33: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 34: CSE 381 – Advanced Game Programming Collision Detection.

Narrow Phase

• What are the contact points on object geometries?– for 3D might be convex hulls

• Two Steps1.determine potentially colliding primitives (ex:

triangles) of a pair of objects• AABB tree algorithms

2.determine contact between primitives• GJK algorithms

• Ref[3]

Page 35: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 36: CSE 381 – Advanced Game Programming Collision Detection.

Velocity Vectors• Velocities have direction, their vector

Vtotal = √(Vx2 + Vy

2 + Vz2) for 3D

games

Vtotal = √(Vx2 + Vy

2) for 2D games

Page 37: CSE 381 – Advanced Game Programming Collision Detection.

Acceleration

• 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

Page 38: CSE 381 – Advanced Game Programming Collision Detection.

Trajectory Assumption

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

Page 39: CSE 381 – Advanced Game Programming Collision Detection.

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 + Fy

2 + Fz2) for 3D games

• Ftotal = √(Fx2 + Fy

2) for 2D games

Page 40: CSE 381 – Advanced Game Programming Collision Detection.

Forces can be summed

• Done axis by axis

Fx = F1x + F2x + F3x

Fy = F1y + F2y + F3y

Fz = F1z + F2z + F3z

Page 41: CSE 381 – Advanced Game Programming Collision Detection.

Momentum

• (P) – A property that objects in motion haveP = m * v, measured in kg * m/s

• Force equation can be reduced to:F = dP/dt

Page 42: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 43: CSE 381 – Advanced Game Programming Collision Detection.

Rigid Bodies

• Note: we are only dealing with rigid bodies

• No deformation due to collisions

Page 44: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 45: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 46: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 47: CSE 381 – Advanced Game Programming Collision Detection.

Example• 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

Page 48: CSE 381 – Advanced Game Programming Collision Detection.

Continuous Collision Detection1. For each moving object, compute what grid cells it occupies and

will cross & occupy if its current velocity is added

2. Find the first contact time between each object pair

3. Sort the collisions, earliest first

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

5. Update velocities of collided objects

6. Go back to 1 for collided objects only

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

• Ref[3]

Page 49: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 50: CSE 381 – Advanced Game Programming Collision Detection.

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

A

B

C

D

NO COLLISION COLLISION

Page 51: CSE 381 – Advanced Game Programming Collision Detection.

Be careful of Tunneling

• What’s that?

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

Page 52: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 53: CSE 381 – Advanced Game Programming Collision Detection.

One way to avoid tunneling

• Swept shapes

• Potential problem: false positives– Good really only for early rejection tests

Page 54: CSE 381 – Advanced Game Programming Collision Detection.

Better way to avoid tunneling

• Calculate first contact times

• Resolve contacts in order of occurrence

Page 55: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 56: CSE 381 – Advanced Game Programming Collision Detection.

% 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)

+ y

+ x

Page 57: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 58: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 59: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 60: CSE 381 – Advanced Game Programming Collision Detection.

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)))?

Page 61: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 62: CSE 381 – Advanced Game Programming Collision Detection.

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)

Page 63: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 64: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 65: CSE 381 – Advanced Game Programming Collision Detection.

Sweep & Prune approach

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

1. Calculate position range on x-axis– extract (minX, maxX)

2. Place all (minX, maxX) pairs into array

3. 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

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

5. Pairs that overlapped on all 3 tests collided

Page 66: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 67: CSE 381 – Advanced Game Programming Collision Detection.

Picking

• 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

Page 68: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 69: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 70: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 71: CSE 381 – Advanced Game Programming Collision Detection.

Recursively finding triangles pseudocodevoid 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; } } else { for each child of node do DoPick(child, ray, results); } }}

Page 72: CSE 381 – Advanced Game Programming Collision Detection.

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

Page 73: CSE 381 – Advanced Game Programming Collision Detection.

References

• [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

Page 74: CSE 381 – Advanced Game Programming Collision Detection.

References

• [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

Page 75: CSE 381 – Advanced Game Programming Collision Detection.

References

• 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