780 likes | 1.13k Vues
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?.
E N D
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? • 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? • 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? • 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 • 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 • 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 • Object versus plane (navigation or culling) • Object versus object (general collision) • Linear component versus object (picking)
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? • 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 • 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 • This is a huge topic • Game physics is rapidly changing
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 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? • 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 • 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 • 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 • 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 • 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 • 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 • 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? • We can have 2 AABBs • Don’t test them against each other
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
Octree • Source: http://en.wikipedia.org/wiki/Image:Octree2.png
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 • 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 • 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 • 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 • Advantages • easy to implement • very fast (computationally inexpensive) • Only good for certain types of predicatable collisions • Physics simulations require more complex approaches
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
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 • 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 • 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 • 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 • Velocities have direction, their vector Vtotal = √(Vx2 + Vy2 + Vz2) for 3D games Vtotal = √(Vx2 + Vy2) for 2D games
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
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 • 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 • Done axis by axis Fx = F1x + F2x + F3x Fy = F1y + F2y + F3y Fz = F1z + F2z + F3z
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
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 • Note: we are only dealing with rigid bodies • No deformation due to collisions
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? • 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)
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
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 • 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 • 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