Download presentation
Presentation is loading. Please wait.
Published byKerry Osborne Modified over 9 years ago
1
CSE 381 – Advanced Game Programming Collision Detection
2
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)
3
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
4
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
5
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
6
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…)
7
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
8
Types of Collisions Object versus plane (navigation or culling) Object versus object (general collision) Linear component versus object (picking)
9
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
10
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.
11
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
12
Collision Detection Game Physics This is a huge topic Game physics is rapidly changing
13
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
14
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)
15
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
16
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
17
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)
18
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
19
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]
20
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)
21
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
22
How about a big, complicated object? We can have 2 AABBs –Don’t test them against each other
23
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.
24
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
25
Octree Source: http://en.wikipedia.org/wiki/Image:Octree2.pnghttp://en.wikipedia.org/wiki/Image:Octree2.png
26
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
27
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
28
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”
29
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
30
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
31
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
32
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)
33
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
34
Narrow Phase What are the contact points on object geometries? –for 3D might be convex hulls Two Steps 1.determine potentially colliding primitives (ex: triangles) of a pair of objects AABB tree algorithms 2.determine contact between primitives GJK algorithms Ref[3]
35
Position Calculations New Position with constant velocity: x t = x 0 + (v x * t) y t = y 0 + (v y * t) z t = z 0 + (v z * t) Velocity is a Vector, (v x, v y, v z ), or (v x, v y ) in 2D Example, object at (1, 5), velocity of (4, -3)
36
Velocity Vectors Velocities have direction, their vector V total = √(V x 2 + V y 2 + V z 2 ) for 3D games V total = √(V x 2 + V y 2 ) for 2D games
37
Acceleration Rate of change of velocity New Velocity (vt) with Acceleration: v t = dx/dt = v 0 + (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
38
Trajectory Assumption In a single frame, if no force is exerted upon an object, it will have a constant velocity for that frame
39
Forces and vectors F = ma Collisions produce forces on both colliding objects Forces have direction, their vector –Forces in x, y, & z axes F total = √(F x 2 + F y 2 + F z 2 ) for 3D games F total = √(F x 2 + F y 2 ) for 2D games
40
Forces can be summed Done axis by axis F x = F 1x + F 2x + F 3x F y = F 1y + F 2y + F 3y F z = F 1z + F 2z + F 3z
41
Momentum (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
42
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
43
Rigid Bodies Note: we are only dealing with rigid bodies No deformation due to collisions
44
Calculating new velocities Note: –ignore rotation/angular velocities for now –ignore centers of mass for now 2 moving blocks collide: –Block A: m A & v Ai –Block B: m B & v Bi Question, if they collide, what should their velocities be immediately after the collision? –v Af & v Bf
45
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
46
Calculating v Af & v Bf If momentum is conserved after collision: P Ai + P Bi = P Af + P Bf (m A * v Ai ) + (m B * v Bi ) = (m A * v Af ) + (m B * v Bf ) Problem has 2 unknowns (v af & v bf ) –we need a second equation (Kinetic energy equation) –ke = (m * v 2 )/2, where ke is never negative Joules (J) –insert the ke equation into our momentum equation v Af = ((2 * m B * v Bi ) + v Ai * (m A – m B ))/(m A + m B ) v Bf = ((2 * m A * v Ai ) – v Bi * (m A – m B ))/(m A + m B )
47
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.xlsElasticCollisionsVelocityCalculator.xls
48
Continuous Collision Detection 1.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]
49
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
50
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 COLLISIONCOLLISION
51
Be careful of Tunneling What’s that? An object moves through another object because collision is never detected
52
A note about timing If we are running at 30 fps, we are only rendering 1/30 th 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
53
One way to avoid tunneling Swept shapes Potential problem: false positives –Good really only for early rejection tests
54
Better way to avoid tunneling Calculate first contact times Resolve contacts in order of occurrence
55
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
56
% 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
57
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
58
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
59
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)
60
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)))?
61
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
62
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)
63
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 UniversityDynamic Simulation of Non- Penetrating Rigid Bodies, (Ph. D thesis)
64
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
65
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(N 2 ). 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
66
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
67
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
68
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
69
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
70
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
71
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; } else { for each child of node do DoPick(child, ray, results); }
72
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
73
References [1] Real Time Collision Detection by Christer EricsonReal Time Collision Detection [2] Physics for Game Programmers by Squirrel EiserlohPhysics for Game Programmers [3] Collision Detection in Interactive 3D Environments by Gino van den Bergen
74
References [1] Real Time Collision Detection by Christer EricsonReal Time Collision Detection [2] Physics for Game Programmers by Squirrel EiserlohPhysics for Game Programmers [3] Collision Detection in Interactive 3D Environments by Gino van den Bergen
75
References Advanced Collision Detection Techniques –http://www.gamasutra.com/features/20000330/bobic_01.htmhttp://www.gamasutra.com/features/20000330/bobic_01.htm N-Tutorials: Collision Detection & Response –http://www.harveycartel.org/metanet/tutorials/tutorialA.htmlhttp://www.harveycartel.org/metanet/tutorials/tutorialA.html Physics in BSP Trees: Collision Detection –http://www.devmaster.net/articles/bsp-trees-physics/http://www.devmaster.net/articles/bsp-trees-physics/ 3D Game Engine Design by David H Eberly
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.