410 likes | 507 Views
CS425 Lecture 10. Jan M. Allbeck. Slides based on those by Graham Morgan. Tonight. Evaluations Simple collision detection A bit of OpenGL by NeHe [I stop by 8:30 (maybe 8:45)] Group work time! Here in Robinson next week too. Collision Detection. Objectives –
E N D
CS425 Lecture 10 Jan M. Allbeck Slides based on those by Graham Morgan
Tonight • Evaluations • Simple collision detection • A bit of OpenGL by NeHe • [I stop by 8:30 (maybe 8:45)] • Group work time! • Here in Robinson next week too.
Collision Detection • Objectives – • Understand what is meant by the term collision detection. • Understand the limitations of collision techniques. • Realize methods for gaining greater levels of collision detection when dealing with irregular shaped objects. • Gain a greater appreciation for LINEAR ALGEBRA
What is collision detection? • Entities occupy, partially or fully, the same location at the same time. • We term the above scenario a collision. • Collision leads to event(s) in most cases – • Bullet hitting a box of grenades causing the event of explosion and possibly other events (e.g., reduction of life force for players stood near the grenades at time of explosion). • However, this is not the full story – • Ideally we should foresee collision as immanent and time our event to occur at a deterministic point in time (true collision). • Q: How is this achieved while still maintaining performance? • A: With great difficulty when performance permits.
Text represented world (Easy) • We move into a new location, each location is textually represented via description. • Entities in the same location are simply considered “collided”. • Once collision has occurred then other actions may be achieved (i.e., interact with other entities present in the location – e.g., chat). • Text based adventure games (e.g., classic games such as The Hobbit on the ZX architectures) may present some descriptive pictures. • Round based games (e.g., Civilization – military units in the same space fight).
Graphically represented world • Check to see if the edges of your entity cross the edges of another entity • If they do then cause collision event. • Slightly complicated when we don’t really want to show intersection (e.g., foot going through wall): • Bounding box (or sphere) introduced: • Check for collision with vectors of bounding box (or sphere). • Cheating in 2D: • In quite a static environment, check to see if pixels of an entity change color – draw background last. This approach popular with 80’s 2D arcade style games as resolution was low. Color was often used to identify items (good or bad).
A problem with frame rate and collision • An entity moves around the screen at a given speed. This speed may be increasing, decreasing (accelerating or decelerating) or may be static. • If the speed of an entity is such that the distance moved on screen is sufficiently large per frame rate, then simply identifying if vertices cross is not an appropriate solution. • They may never cross! Entity Solid wall Frame 1 Frame 2
E1 E2 E2 E1 Considering time in collision detection • Assume entities E1 and E2 are displayed in different positions at the following frame times t1, t2 (giving the illusion of motion). t1 t1 • We know they collided, but as far as the display is concerned no collision has occurred. (they have passed through each other). • We need to introduce the notion of time into our equations to aid collision detection.
Possible solutions – Projecting bounding box. • Produce bounding box around an entity at current frame and next frame position (look ahead) and check collisions using this new shape. • For this method to work we are actually carrying out twice as much detection as required. This is very time consuming and will possibly reduce performance (even slower frame rate).
Possible solutions – Using time in our equations • Use a recursive algorithm to check for intersection at lower time intervals (even though these will not be displayed on screen). • Carry out our calculations in 4D (including time). This is complicated physics and computationally draining of valuable CPU time. • In real-time games (such as first person shooters) these types of calculations are just too intensive.
Using a sphere • We surround our entity with a large enough sphere to ensure that collisions (in the most part) are detected. • When projected into consecutive frames, the spheres should overlap. • This ensures we cover the whole (well nearly whole) scope of the possible collision. • We check if the distance between the two centres of the spheres is less than the sum of the radii. • However, while the calculations are simple, the results can look poor on screen (collision events may occur when the user actually views no collision).
More precise detection • When entities are an irregular shape, a number of spheres may be used. • In this diagram we use three spheres for greater accuracy. • Geometry in games may be better suited to bounding boxes (not circles). • To ease calculations, bounding boxes are commonly axis aligned (irrelevant of entity transformations they are still aligned to X, Y and Z coordinates in 3D) These are commonly called AABBs (Axis Aligned Bounding Boxes).
Spheres • Axis aligned bounding boxes (AABB) • Object aligned bounding boxes (OABB) Bounding Boxes/Volumes • In general, OABB fit tighter than AABB, which fit tighter than spheres. • But AABB is the easiest to compute: just max and min each coordinate…
Computing the Axis-Aligned Bounding Box Let AABB be the 2x2 matrix: To construct the AABB values: bool SetBoundingBox(const gMatrix& V, const gMatrix& AABB){ int i; AABB[0][0] = AABB[0][1] = V[0][0]; AABB[1][0] = AABB[1][1] = V[1][0]; for (i = 1; i = V.cols()-1; i++) { if (AABB[0][0] > V[0][i]) AABB[0][0] = V[0][i]; if (AABB[0][1] < V[0][i]) AABB[0][1] = V[0][i]; if (AABB[1][0] > V[1][i]) AABB[1][0] = V[1][i]; if (AABB[1][1] < V[1][i]) AABB[1][0] = V[1][i]} }
Combining Algorithms for Greater Efficiency • If point is outside polygon bounding box, then point is outside polygon; Otherwise do PointInPoly test. • More elaborate combination algorithms are possible.
Point Inside Polygon Algorithm Adapted from Shimrat: Collected Algorithms of ACM, #112, Aug. 1962, p.434 Input: polygon and test point Output: PointInPoly true if point is inside polygon, otherwise false Note: this algorithm is possibly ambiguous if the point is on or almost on an edge of the polygon. Accordingly, it is best to test if the point lies on any polygon edge first before running the inside test, if the results need to be accurate. Also, if the polygon contains horizontal line segments and the point lies on such a horizontal segment, the answer may vary. These two cases are fixable, but are left as an exercise.
bool PointInPoly(const gMatrix& polygon, const gVector& point){ bool inside = false; gVector p1; gVector p2; for (i = 0; i<polygon.cols()-1; i++){ // iterate through each edge p1 = polygon.getCol(i); //get first edge endpoint from polygon p2 = polygon.getCol(i+1); // get second edge endpoint from polygonif (p1[1] > p2[1]) swap(p1, p2); //want p1 to p2 to point in +y direction if (point[1] > p1[1]){ //above lower edge endpoint if (point[1] <= p2[1]){ //below upper edge endpoint if (p1[1] != p2[1]){ //if edge is not horizontal do half-plane check // z of crossproduct(point-p1, p2-p1) > 0) means we’re to the right if ((point[0] - p1[0]) * (p2[1] - p1[1]) – ((p2[0] - p1[0]) * (point[1] - p1[1]))) > 0)inside = !inside // if true, point is to right of edge (and thus in the “strip”) } } } return inside; }
Bounding Boxes Used for Test Efficiency bool PointInPolyWithBoundingBoxCull(const gMatrix& polygon, const gMatrix& BoundingBox, const gVector& point ){ if ((point[0] <= BoundingBox(xmin)) ║ (point[0] >= BoundingBox(xmax)) ║ (point[1] <= BoundingBox(ymin)) ║ (point[1] >= BoundingBox(ymax))) return false elsereturn PointInPoly(polygon, point) }
Extend Scene Graph Node with Bounding Boxes Transformation Matrix [.] Bounding Box Child [vector of tree or geometry pointers] • Alternative bounding box representations may be stored. • Bounding box must be re-evaluated after transformation is applied to child geometry. • Can use “dirty-bit” to avoid recomputing all lower BBs if a middle scene graph transformation is changed but intersection tests are not yet needed. Bounding Box data (e.g. OBB) Min-x Max-x Min-y Max-y
Hierarchical Bounding Boxes (or Volumes) • Use hierarchical bounding boxes to avoid detailed edge by edge intersection tests. • Group objects any reasonable way: by complex areas, by natural parts, by proximity, by scene graph node, etc.
Recursive testing of bounding boxes • We can build up a recursive hierarchy of bounding boxes to determine quite accurate collision detection. • Here we use a sphere to test for course grain intersection. • If we detect intersection of the sphere, we test the two sub bounding boxes. • The lower bounding box is further reduced to two more bounding boxes to detect collision of the cylinders.
Tree structure used to model collision detection • A recursive algorithm can be used to parse the tree structure for detecting collisions. • If a collision is detected and leaf nodes are not null then traverse the leaf nodes. • If a collision is detected and the leaf nodes are null then collision has occurred at the current node in the structure. • If no collision is detected at all nodes where leaf nodes are null then no collision has occurred (in our diagram B, D or E must record collision). B A A D B C C D E E
Speed over accuracy • The approach which offers most speed would be to have AABBs of a size fixed at entity initialization time. • That is, irrelevant of entity transformation the associated AABB does not change in size or shape. • This is cumbersome for entities shaped like cylinders. • Plenty of “free space” will exist around the cylinder. • For more realistic collision detection the bounding box may fit closely to the entity and rotate along with associated entity. • This requires the bounding box to be recomputed every time an entity is rotated.
Line – Polygon Intersection • For each polygon edge, compute intersection of line with edge and test if intersection is “real”. • If polygon is “complicated”, can use (hierarchical) bounding boxes to advantage in “busy” (edge-rich) regions of its boundary. • Note that if the line is directed (a ray, for example), we may need to find the first intersection with the polygon. Think “projectile”.
Collision Detection • Intersection of a particle path with a (polygonal) object. • Intersection of a infinitesimal (point) particle with a polygonal object. • Intersection of a disk with a polygonal object. • Not just a “object inside another object test”: Oops… t0 t1 t2 t3
Collision Detection • Intersection of a particle path with a (polygonal) object. • Intersection of a infinitesimal (point) particle with a polygonal object. • Intersection of a disk with a polygonal object. • Not just a “object inside another object test”: t3-t2 t2-t1 t1-t0
Intersection Detection • Essentially find minimum distance between two geometric sets (don’t even have to be polyhedral): • If distance is positive, then no intersection (collision). • If distance is 0, then they touch (collide). • If distance is negative, then they interpenetrate.
Geometric Intersection Detection • Dynamic intersection requires that we consider the path in between frame (test) times! • Linear interpolate to find point of intersection, hence intersection time. • Since this time is unlikely to be exactly at a frame time, we have to do some calculation to figure out where the particle would be a the next frame time after the collision. • This is not difficult once we establish what the result of the collision should be.
Collision Response • At intersection point, compute edge normal direction vector. • Reflect particle path around this normal. • Maintain same speed out as in (not physically correct, but easier). • Thus particle position is computed as the same velocity just along a path with a reflection.
Finding the Edge Normal at Point P -N Vi+1 = (xi+1, yi+1) P N= (Nx, Ny) Vi = (xi, yi) (Usually want outward-facing normal.) Nx = yi+1 – yi Ny = – (xi+1 – xi) =xi – xi+1 (This is just rotation of the edge vector by -90°.)
Reflection about a Surface Normal N = Surface normal at point P Ri = Incident ray direction (unit vector) at point P. Rr = Reflected ray direction (unit vector) at P around N. Rr = Ri – 2 N (Ri• N) N Ri Rr Ø Ø Surface P [Check: If Ri║N (i.e., Ri= – N) then Rr= N ; if Ri┴ N then Rr= Ri ]
Bouncing a Particle by Reflection • If distance from particle to object is less than its interframe motion, then find the intersection point Q and the intersection time t (0 < t < t) and split the motion into two successive pieces. That determines where the particle will be at the next frame. • P1 is then readily computed as . N P0 P1 Ø Ø Q P1
But… • Life is never simple, since there could be some geometry intersecting this new path QP1. • So have to repeat this computation until there is no such intersection! More geometry P0 P1 N P1 Q P1
What if the Particle is a Disk? • If the particle is a disk of finite radius, then we need to calculate the intersection of the disk with the object geometry. • Use the radius in the collision distance test. • But note that the object edge hit first might not be the one that lies directly in its path!: First intersection!
Disk vs. Polygon Collision • We must check intersection of the disk’s path against ALL edges of the object to determine which one will be hit first (that is, which is the closest to the disk). • This changes the surface the collision is reflected from, but otherwise the computation of the reflected direction vector (and the possibility of hitting another object edge or edges before the next frame time!) is the same as before. • If the moving object is a polygonal shape, things get even more interesting. We’ll check out this case, too.
Disk moving inside Polygon • Suppose we have a disk moving inside a polygon and “bouncing” off the edges. • Tomas Lozano-Perez invented a clever algorithm: change the disk/polygon collision into the (simpler) point particle/polygon problem by offsetting (sliding) the polygon boundary by the disk’s radius:
NeHe Collision example http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=30
Obstacle Avoidance and Steering Behavior http://www.red3d.com/cwr/steer/
Collision Detection in DarkGDK Documentation
Some of what I’ll be looking for… • DOCUMENTATION (5pts) • Navigation (5pts) • Different NPCs (3pts) • Robots • Hostages • Hostiles • Different actions (2pts) • Walk, pick up, detonate, freeze, etc • Different AIs (5pts) • Player interface (5pts) • Object oriented design (3pts) • Interesting environment: layout and objects (2pts) • Integration/group work (3pts) • Impression of work put in (2pts) • Playable, fun (3pts) • Extras/polish (2pts) • Total = 40 pts (+ 10 from previous assignment)