animation and games development
DESCRIPTION
Animation and Games Development. 242-515 , Semester 1 , 2014-2015. Objective to discuss some of the basic issues related to collision detection and collision response. 13. Collision Detection. Overview. Collision Detection Uses 2 . Collision Algorithms 3. Spatial Partitioning - PowerPoint PPT PresentationTRANSCRIPT
242-515 AGD: 13. Collisions 1
• Objectiveo to discuss some of the basic issues related to collision
detection and collision response
Animation and Games
Development242-515, Semester 1, 2014-2015
13. Collision Detection
Overview9. Where do Objects
Touch?10. Collision Response
Algorithms11. Collision Changes12. Momentum and
Collisions13. Complex Collisions14. More Collision Issues15. Summary
1. Collision Detection Uses
2. Collision Algorithms
3. Spatial Partitioning4. Simplifying Shapes5. Terrain Collision6. Collision Time7. The Tunneling
Problem8. More Complex
Tunneling Solutions
242-515 AGD: 13. Collisions 3
• Determine if the player has a hit a wall or obstacle
• Determine if a missile has hit a target• Detect when things should change
o e.g. a hand touches a light switch• Clean up animation
o Make sure a character’s feet touch the floor• To help implementing realistic motion
o E.g. of cloth, water, fire
1. Collision Detection Uses
242-515 AGD: 13. Collisions 4
• Collision Detectiono Check for the intersection of two objects
o Calculate the trajectories of the objects, impact times, and impact points
• Collision Responseo provide a response that fits the game and (customized) laws of
physics
Collision Detection and Response
242-515 AGD: 13. Collisions 5
• Main character and static objects:o terrain, floor, walls, furniture, buildings, etc.
• Main character and dynamic objects:o enemies, bullets, arrows, particles, etc.
• Dynamic game objects (e.g. enemies) and static and other dynamic objects.
Types of Collisions
2. Collision Algorithms• Shapes can be very complex,
potentially requiring expensive testing:o points, line, convex/concave objects
• Shapes move in different ways:o Use different algorithms for fast
or slow moving objectso The algorithms will also depend
on how frequently an object must be updated
Convex Concave
An object is convex if for every pair of points
inside the object, the line joining them is also
inside the object
242-515 AGD: 13. Collisions 7
• Design principles for collision algorithms.
• Fast simple tests first to eliminate most potential collisionso e.g.: test bounding volumes before complex shapes
• Exploit locality to eliminate many potential collisionso e.g. use spatial partitioning to avoid testing two
objects that are far apart
Design Principles
242-515 AGD: 13. Collisions 8
• Use as much geometry information as possibleo e.g. spheres have special properties that make collision
testing faster
• Exploit coherence between successive testso coherence means that things (objects) tend to stay the
same over time
242-515 AGD: 13. Collisions 9
• Compare all game objects against all other objects, one pair at a time
• This approach is easy to understand and to implement.
• But it is slow -- O(n2) running time since every object can potentially collide with every other object.
Collisions in Pairs
242-515 AGD: 13. Collisions 10
• Include non-collidable objects in your game:o background: sky, clouds, grass, etco dead enemies (maybe)o unimportant game objects
• No need to include in collision testing, so speeds up the game.
Non-collidable Objects
Collision Challenges• Question:
o Do objects A and B intersect
Collision Challenges• Question:
o Do objects A and B intersect
• Challenge:o Can be in motion
Collision Challenges• Question:
o Do objects A and B intersect
• Challenge:o Can be in motion
• Bigger Challenge:o Need to know when
they collide.o Realistic physics needs
the exact point of collision
o Necessary for collision response
242-515 AGD: 13. Collisions 14
• Priori: check if something is going to collide before moving it, then make the necessary correction
• Posteri: check if something has collided and make the necessary corrections
Time-based Techniques
242-515 AGD: 13. Collisions 15
• Common types of spatial partitioning:o Octrees (called quadtrees in 2D)
o Uniform Grids
o Others types: portals (used in Quake), BSP trees (Binary Space Partitions), spatial hashing
3. Spatial Partitioning
242-515 AGD: 13. Collisions 16
An Octree
game regions
game regions
242-515 AGD: 13. Collisions 17
• Data stored in each region:o coordinates defining the region
• though a smart implementation can greatly simplify this
o a list of objects inside a region
242-515 AGD: 13. Collisions 18
• Dynamic objects may move between regionso this requires the octree to be updated
• A static (or dynamic) object may be positioned so it spans several regionso collision detection will involve objects from multiple regions
Octree Drawbacks
242-515 AGD: 13. Collisions 19
• Steps:o divide the (2D or 3D) world into a grid of equal sized
cells
o associate each object with the cells it is located inside
o only objects sharing a cell are tested for collisions
Uniform Grids
242-515 AGD: 13. Collisions 20
• What cells does the object currently occupy?
• Possible calculations:o For min/max tile rows/columns:
• sprite.X/tileWidth• sprite.Y/tileHeight• (sprite.X+sprite.Width)/tileWidth• (sprite.Y+sprite.Height)/tileHeight
• For the 'man' object in cells (0,0), (0,1), (1,0), (1,1)o only test against:
• other objects in those cells• also, don’t let an object occupy “collidable cells” (0,2), (1,2), etc
Calculating a Grid Position
0 1 2 3
0
1
2
242-515 AGD: 13. Collisions 21
• Advantageso easy to implemento very fast: O(n)
• Disadvantageso constrains look of game to a grid-like world
242-515 AGD: 13. Collisions 22
• Typically divide an object into convex shapeso Mathematically the easiest
shapes to compute with• Assumed by most algorithms
• What do you do if the shape is not convex?o Break it up into several parts
4. Simplifying Shapes
242-515 AGD: 13. Collisions 23
• A simple geometry used in the collision tests instead of the shape’s real, complicated geometry.
• Properties of good BVs:o inexpensive collision testso tight fit to the original shapeo inexpensive to createo easy to rotate and transformo uses little memory
Bounding Volumes (BVs)
242-515 AGD: 13. Collisions 24
• AABBs: axis-aligned bounding boxes• OBBs: Oriented bounding boxes• DOPs: Discrete oriented polytopes
Common Bounding Volumes
242-515 AGD: 13. Collisions 25
In 3D
Ax is - Alig n ed Bo u n d in g Bo x O r ien ted Bo u n d in g Bo x
242-515 AGD: 13. Collisions 26
AABBs• Axis Aligned Bounding-
Boxes (AABBs)o Intersection is very cheap
• Project rectangle onto axeso Two intervals per box
• Check both intervals overlap
o Poor fit for most objects
242-515 AGD: 13. Collisions 28
• Common solution:o axis separation test
• More sophisticated solution:o Plane Sweep: an extension of axis separation which is more
efficient when dealing with many objects
Do AABB's Collide?
242-515 AGD: 13. Collisions 29
• How do we know if two AABBs are colliding?o their edges overlap on all axes
Axis Separation Test
A
B
C
D
NO COLLISION COLLISION
242-515 AGD: 13. Collisions 30
• Requires sorting of the objects along the axes• Running time: O(n)
C
B
R
A
x
y
A 0 A 1 R 0 B0 R 1 C 0 C 1B1
B0
B1A 1
A 0
R 1
R 0
C 1
C 0
Plane Sweep
OBBs• Oriented Bounding
Boxes (OBBs)o Tighter fit than AABBo Intersection more
expensive• Must check 4 edges
for overlap
DOPs
• Discrete Oriented Polytopes (DOPs)o Captures almost all
convex shapes
o Intersection is more expensive
• O(a2), a = number of edges
Capsule• Capsule
o An OBB with rounded ends
o Intersection cost is roughly the same
o Efficient for swept shapes
Circles/Disks
• Circles/Diskso Not cheaper than AABB
o Poor fit for anything other than a circle
242-515 AGD: 13. Collisions 35
• We can use two AABBs to represent the objecto Don’t test them against each other
How about a Complicated Object?
242-515 AGD: 13. Collisions 36
• Complex objects can have multiple bounding boxeso e.g. a Human object can have one big bounding box
covering the whole body; oro one bounding box per limb, head, etc
• Bounding boxes can be hierarchical:o Test the big 'human' box firsto If there is a possible collision, test the smaller boxes
inside the big one (e.g. the limb, head boxes)
Multiple Bounding Boxes
242-515 AGD: 13. Collisions 37
• Build a tree of boxes:o a parent box surrounds all the boxes of its children
• Intersection test against a bounding box tree by travelling down the tree to a leaf box.
• Generally used to test a moving object against lots of static obstacleso Put all the static obstacles into one large box tree
Bounding Box Hierarchies
242-515 AGD: 13. Collisions 38
• Utilizes the heightmap information, and the fact that the terrain is a mesh of triangles.
5. Terrain Collision
242-515 AGD: 13. Collisions 39
T o p - D o wn Vie w
P e r sp e c t iv e Vie w
T o p - D o wn Vie w ( h e igh t s a dde d)
P e r sp e c t iv e Vie w ( h e igh t s a dde d)
Terrain Mesh and Heights
242-515 AGD: 13. Collisions 40
Locate Triangle on Mesh
Q
R
Q
Q z > Q x
Q z < = Q x
z
x
R z > 1 - R x
R z < = 1 - R x
R
Simplifies to a 2D problem of points inside triangles.
242-515 AGD: 13. Collisions 41
• We can use Barycentric coordinates to test if a point is inside a triangle.
Barycentric Coordinates
P 1
P 2
P 0
Q
P o in t = w 0P 0 + w 1P 1 + w 2P 2
Q = ( 0 ) P 0 + ( 0 .5 ) P 1 + ( 0 .5 ) P 2
R = ( 0 .3 3 ) P 0 + ( 0 .3 3 ) P 1 + ( 0 .3 3 ) P 2R
242-515 AGD: 13. Collisions 42
• Given a ball with center at position p0 = (x1, x2, x3), with initial velocity v = (v1, v2, v3), and a constant acceleration a = (a1, a2, a3).
• When will its center hit a plane defined by f(x, y, z) = 0 ?o p = p0 + vt + ½ at2
o Solve the equation f(p) = 0
6. Collision Time
242-515 AGD: 13. Collisions 43
• If the game is running at 30 fps, it only renders 1/30th of the object's stateso sometimes called the Flipbook syndrome
• Many things happen that we don’t see
Time Interval Problem
We don’t see the ball hit the ground
242-515 AGD: 13. Collisions 44
• An object moves through another object because the collision testing is not done at the 'right' time:
7. The Tunneling Problem
time: 5 6 7 8
Tunneling
Tunneling Example
Tunneling
Tunneling
242-515 AGD: 13. Collisions 49
• Things can fall through the floor
• Cars can pass through people or walls
• Players can enter rooms with no doors
• Players can travel over holes
• etc...
Tunneling is a Big Problem
242-515 AGD: 13. Collisions 50
• Small objects can tunnel more easily than large shapes:
Tunneling
242-515 AGD: 13. Collisions 51
• Simple solutionso Minimum size requirement?
• Inadequate; fast objects can still tunnel
Tunneling
242-515 AGD: 13. Collisions 52
• Simple solutionso Minimum size requirement?
• Inadequate; fast objects can still tunnel
o Maximum speed limit?• Inadequate; speed limit is a function of object size, so
small and fast objects (bullets) wouldn’t be allowed
o Smaller time step?• Helpful but inadequate; same problem as a speed
limit
Tunneling
242-515 AGD: 13. Collisions 53
• Movement Bounds• Swept Shapes• Minkowski Sums• Interval Halving
8. More Complex Tunneling Solutions
8.1. Movement Bounds• Disc / Sphere
Movement Bounds• Disc / Sphere• AABB
Movement Bounds• Disc / Sphere• AABB • OBB
Movement Bounds• Question:
o Could A and B have collided during the frame?
• It handles tunneling, but…
Movement Bounds• Question:
o Could A and B have collided during the frame?
• It handles tunneling, but…• … even if the answer is
“yes”, we still don’t know for sure
242-515 AGD: 13. Collisions 59
• Conclusionso Good: it prevent tunnelingo Good: cheap, effective, early rejection test
o Bad: it produces false "yes" answers for collision tests• called a "false positive"
Movement Bounds
8.2. Swept Shapes• Swept disc: capsule
Swept Shapes• Swept disc: capsule• Swept AABB:
polygon
Swept Shapes• Swept disc: capsule• Swept AABB:
polygon• Swept triangle:
polygon
Swept Shapes• Swept disc: capsule• Swept AABB:
polygon• Swept triangle:
polygon• Swept polytope:
polygon
Swept Shapes• Better fit than
movement bounds
Swept Shapes• Better fit than
movement bounds• No false negatives
(tunneling)
Swept Shapes• Better fit than
movement bounds• No false negatives
(tunneling)• No false positives
either!
Swept Shapes• Better fit than
movement bounds• No false negatives
(tunneling)• No false positives
either!
• No! False positives still exist
242-515 AGD: 13. Collisions 68
• By taking the Minkowski sum of two complex volumes and creating a new volume, the overlap can be found by testing if a point is within the new volume.
8.3. Minkowski Sums
Y}B and :{ XABAYX
X Y =YX X Y =
242-515 AGD: 13. Collisions 69
Using the Minkowski Sum
t0
t1
t0
t1
The sphere and box objects become a point and the Minkowski sum.
8.4. Interval Halvingt=0
t=1
t=0.5
t=1
t=0.5t=0.75
t=0.5t=0.625
t=0.5625
Sometimes called Bisect Testing
242-515 AGD: 13. Collisions 71
• You know when the objects were not touching(the last frame)
• You know when they are colliding(this frame)• So you have an upper and lower bound on the collision
time
• Bring these bounds closer together• Check for a collision at the midpoint of the current time
intervalo If there is a collision, the midpoint becomes the new upper
boundo If not, the midpoint is the new lower bound
• Keep going until the bounds are the same (or accurate enough)
242-515 AGD: 13. Collisions 72
• What are the contact points on object geometries?
• Most common approach is the Gilbert-Johnson-Keerthi (GJK) algorithm:o a complex algorithm that combines linear algebra,
determinants, and Minkowski sums
9. Where do Objects Touch?
242-515 AGD: 13. Collisions 73
• What happens after a collision?o It depends on the collision type: elastic and inelastic
• Inelastic collisions (no rebound)o No energy preserved in collisiono Easy to implement
• Elastic collisions (there is rebound/bouncing)o 100% energy preservedo More complicated to implement. Must introduce momentum
10. Collision Response Algorithms
242-515 AGD: 13. Collisions 74
• Two billiard balls strike each othero Calculate balls positions at the time of impacto Assign new velocities to the ballso Play a “clinking” sound
• A rocket hits a wallo The rocket disappearso Create an explosion effect, and play an explosion
soundo Change the wall texture to show damage
Collision Response Examples
242-515 AGD: 13. Collisions 75
• Response coding often has three parts:1. Prologue (before)2. Collision Changes3. Epilogue (after)
• Many visual effects can be done in the prologue or epilogue
Collision Response in Parts
242-515 AGD: 13. Collisions 76
• Collision known to have occurred
• Check if collision should be ignored
• Other events might be triggeredo Sound effectso Send collision notification messages
Prologue
242-515 AGD: 13. Collisions 77
• Place objects at point of impact
• Assign new velocitieso Using physics oro Using some other decision logic
Collision Changes
242-515 AGD: 13. Collisions 78
• Propagate post-collision effects
• Possible effectso Destroy one or both objectso Play sound effecto Inflict damage
Epilogue
11. Collision Changes
• What happens to the objects after colliding?
• Two basic approacheso Instantaneous change of objects velocities at
collision time
o Gradual change of their velocities and positions over time, following their collision
242-515 AGD: 13. Collisions 80
• Benefits:o The change can be calculated using fairly simple
equations
• Difficulties:o The precise detection of the time and location of the
collision can be expensive (a frame rate killer)o The coding to manage the necessary objects state is
complex
Instantaneous Change
Gradual Change• Benefits
o Does not require the precise detection of the time and location of the collision
o State management is easyo May look more realistic (e.g. the object meshes can be
deformed)
• Difficultieso Object interpenetration is likely, and hard to calculate (e,g,
may need finite difference methods)
Simple Case: Circles• Simple collisions
o Single point of contact
• Impact coordinateso Point of contact is origin
Simple Case: Circles• Simple collisions
o Single point of contact
• Impact coordinateso Point of contact is origin
Simple Case: Circles• Simple collisions
o Single point of contacto Rigid bodies
• Impact coordinateso Point of contact is origino Perpendicular componento Parallel component
Simple Case: Circles• Simple collisions
o Single point of contacto Rigid bodies
• Impact coordinateso Point of contact is origino Perpendicular componento Parallel component
• Change in motion happens along the perpendicular axis
Simple Case: Circles• Simple collisions
o Single point of contacto Rigid bodies
• Impact coordinateso Point of contact is origino Perpendicular componento Parallel component
• Exchange in energy happens along the perpendicular axis
242-515 AGD: 13. Collisions 87
• Momentum transfer – if two objects collide:o A perfectly elastic collision: no loss of energy
• Momentum is conserved
o An imperfect elastic collision: some energy is converted into heat, work, and deformation of objects
• Momentum is reduced after collision
12. Momentum and Collisions
242-515 AGD: 13. Collisions 88
• Note: o ignore rotation/angular velocitieso ignore centers of mass (treat as points)
• Two moving balls collide:o ball A: mA and vAi
o ball B: mB and vBi
• If they collide, what should their velocities be immediately after the collision?o vAf and vBf
Calculating New Velocities
242-515 AGD: 13. Collisions 89
• If momentum is conserved after the collision:PAi + PBi = PAf + PBf
(mA * vAi) + (mB * vBi) = (mA * vAf) + (mB * vBf)
• Problem has two unknowns (vaf and vbf)o we need a second equation (Kinetic energy equation)o ke = (m * v2)/2, where ke is never negative Joules (J)o Insert the ke equation into the momentum equation
vAf = ((2 * mB * vBi) + vAi * (mA – mB))/(mA + mB)
vBf = ((2 * mA * vAi) – vBi * (mA – mB))/(mA + mB)
Calculating vAf and vBf
242-515 AGD: 13. Collisions 90
• Ball A: o mass is 10, initial velocity is (4, 0)
• Ball B:o mass is 10, initial velocity is (-4, 1)
• Results:o BallA's final velocity is (-4, 1)o Ball B's final velocity is (4, 0)
Example
13. Complex Collisions• With complex shapes,
the point of contact is more complexo Could be a single pointo Could be an edge
• Solution:o Break object into several pointso Connect the points by
constraintso Apply forces to each of the
pointso Transfer forces to other points
while obeying constraints
• Requires a constraint solver
• With complex shapes, the point of contact is more complexo Could be a single pointo Could be an edge
• Solution:o Break object into several pointso Connect the points by
constraintso Apply forces to each of the
pointso Transfer forces to other points
while obeying constraints
• Requires a constraint solver
• Multiple simultaneous collision points• Articulated bodies, with joints• Friction• Breakable objects• Soft bodies• Smoke, clouds, gases• Water, oil, fluids
14. More Collision Issues
242-515 AGD: 13. Collisions 94
• Accurate collision detection and response is hard
• Tips:o Structure the game to make collision detection easy
• use circles, AABBs, grids, etc.
o Especially in the 3D case, consider using a physics engine (e.g. jBullet) rather than writing your own collision detection and response code
15. Summary