1 / 75

# - PowerPoint PPT Presentation

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.

## PowerPoint Slideshow about '' - Mia_John

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

### CSE 381 – Advanced Game ProgrammingCollision Detection

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

• Remember what we learned

• Sweep and Prune algorithm (today)

• GJK algorithm (Monday)

• 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

• 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

• 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

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

• 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

• Object versus plane (navigation or culling)

• Object versus object (general collision)

• Linear component versus object (picking)

• 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

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

• 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

• This is a huge topic

• Game physics is rapidly changing

• 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 objects never move

• Dynamic objects move

• Collisions may be between:

• Static objects & dynamic objects (fast & easy)

• Dynamic objects & dynamic objects (harder)

• 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

• 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

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

• 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

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

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

• 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

• We can have 2 AABBs

• Don’t test them against each other

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

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

• 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

• Objects cross islands

• octree has to be constantly updated

• collision detection may involve objects from multiple islands

• 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

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

• 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

• 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

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

• 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

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

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

• 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

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

• 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

• 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

• 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

• Note: we are only dealing with rigid bodies

• No deformation due to collisions

• 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

• When a collision precisely happens, we want to:

• move our objects to that precise location

• change their velocities accordingly

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

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

• 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

• 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

NO COLLISION

COLLISION

A

C

B

D

• What’s that?

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

• 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

• Swept shapes

• Potential problem: false positives

• Good really only for early rejection tests

• Calculate first contact times

• Resolve contacts in order of occurrence

• 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

• 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

• 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

• 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

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

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

• 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

• 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

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

• Also called Sort & Sweep

• 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

• 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

• 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

• 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

• 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

• 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

• 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

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)

}

}

else

{

for each child of node do

DoPick(child, ray, results);

}

}

}

• 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