Basic Game Physics Introduc6on (1 of 2)
Total Page:16
File Type:pdf, Size:1020Kb
4/5/17 Basic Game Physics IMGD 4000 With material from: Introducon to Game Development, Second EdiBon, Steve Rabin (ed), Cengage Learning, 2009. (Chapter 4.3) and Ar)ficial Intelligence for Games, Ian Millington, Morgan Kaufmann, 2006 (Chapter 3) IntroducBon (1 of 2) • What is game physics? – Compung mo)on of objects in virtual scene • Including player avatars, NPC’s, inanimate objects – Compung mechanical interacons of objects • InteracBon usually involves contact (collision) – Simulaon must be real-Bme (versus high- precision simulaon for CAD/CAM, etc.) – Simulaon may be very realisBc, approXimate, or intenBonally distorted (for effect) 2 1 4/5/17 IntroducBon (2 of 2) • And why is it important? – Can improve immersion – Can support new gameplay elements – Becoming increasingly prominent (eXpected) part of high-end games – Like AI and graphics, facilitated by hardware developments (mulB-core, GPU) – Maturaon of physics engine market 3 Physics Engines • Similar buy vs. build analysis as game engines – Buy: • Complete soluBon from day one • Proven, robust code base (hopefully) • Feature sets are pre-defined • Costs range from free to expensive – Build: • Choose eXactly features you want • Opportunity for more game-specificaon opBmizaons • Greater opportunity to innovate • Cost guaranteed to be eXpensive (unless features eXtremely minimal) 4 2 4/5/17 Physics Engines • Open source – BoX2D, Bullet, Chipmunk, JigLib, ODE, OPAL, OpenTissue, PAL, Tokamak, Farseer, Physics2d, Glaze • Closed source (limited free distribuBon) – Newton Game Dynamics, Simple Physics Engine, True AXis, PhysX • Commercial – Havok, nV Physics, VorteX • Relaon to Game Engines – Nave, e.g,. C4 – Integrated, e.g., UE4 + PhysX – Pluggable, e.g., C4 + PhysX, jME + ODE (via jME Physics) Basic Game Physics Concepts • Why are we studying this? – To use an engine effecBvely, you need to understand something about what it’s doing – You may need to implement small features or eXtensions yourself – Cf., owning a car without understanding anything about how it works • EXamples – Kinemacs and dynamics – Projecle moBon – Collision detecBon and response 6 3 4/5/17 Outline • IntroducBon (done) • Kinemacs (next) • The Firing Soluon • Collision DetecBon • Ragdoll Physics • PhysX 7 Kinemacs (1 of 3) • Study of moBon of objects without taking into account mass or force • Basic quanBBes: posion, me • ... and their derivaves: velocity, acceleraon • Basic equaons: Where: 1) d = vt t - (elapsed) )me d - distance (change in posi)on) 2) v = u + at v - (final) velocity (change in distance per unit )me) 3) d = ut + ½at2 a - accelera)on (change in velocity per unit )me) 2 2 u - (ini)al) velocity 4) v = u + 2ad Note, equaon #3 is the integral of equaon #2 with respect to Bme (see neXt slide). Equaon #4 can be useful. 8 4 4/5/17 Kinemacs (2 of 3) Non-accelerated moBon Accelerated moBon d = ut d = ut + ½at2 EXample: EXample: u = 20 m/s, t = 300 s u=0 m/s, a=4m/s2, t=3s d = 20 x 3000 = 6000 m d = 0x3 + 0.5x4x9 = 18m Kinemacs (3 of 3) Predicon Example: If you throw a ball straight up into the air with an iniBal velocity of 10 m/ sec, how high will it go? v = 0 v2 = u2 + 2ad d a = -10 u = 10 m/sec (iniBal speed upward) a = -10 m/sec2 (approX gravity) v = 0 m/sec (at top of flight) u = 10 0 = 102 + 2(-10)d d = 5 meters (Note, answer independent of mass of ball!) 10 5 4/5/17 Doing It In 3D • Mathemacally, consider all quanBBes involving posiBon to be vectors: d = vt v = u + at d = ut + at2/2 • Computaonally, using appropriate 3-element vector datatype 11 Dynamics • NoBce that preceding kinemac descripBons say nothing about why an object accelerates (or why its acceleraon might change) • To get a full “modern” physical simulaon you need to add two more basic concepts: – force – mass • Discovered by Sir Isaac Newton • Around 1700 J 12 6 4/5/17 Newton’s Laws 1. A body will remain at rest or conBnue to move in a straight line at a constant speed unless acted upon by a force. 2. The acceleraon of a body is proporonal to the resultant force acBng on the body and is in the same direcBon as the resultant force. 3. For every acBon, there is an equal and opposite reacBon. 13 MoBon Without Newton’s Laws • Pac-Man or early Mario style – Follow path with instantaneous changes in speed and direcBon (velocity) – Not physically possible • Note - fine for some casual games (especially with appropriate animaons) 14 7 4/5/17 Newton’s Second Law F = ma At each moment in Bme: F = force vector, in Newton’s m = mass (intrinsic scalar property of maer), in kg a = acceleraon vector, in m/sec2 Player cares about state of world (posiBon of objects). Equaon is fundamental driver of all physics simulaons. • Force causes acceleraon (a = F/m) • Acceleraon causes change in velocity Kinemacs • Velocity causes change in posion equaons 15 How Are Forces Applied? • May involve contact – Collision (rebound) – Fricon (rolling, sliding) • Without contact – Rockets/Muscles/Propellers – Gravity – Wind (if not modeling air parBcles) – Magic • Dynamic (force) modeling also used for autonomous steering behaviors 16 8 4/5/17 CompuBng Kinemacs in Real Time start = getTime() // start time p = 0 // initial position u = 10 // initial velocity a = -10 d function update () { // in game loop a = -10 now = getTime() t = now – start simulate(t) } u, p function simulate (t) { 2 d = (u + (0.5 * a * t)) * t d = ut + at /2 move object to p + d // move to loc. computed since start } Note! Number of calls and Bme values to simulate() depend on (changing) game loop me (frame rate) Is this a problem? It can be! For rigid body simulaon with colliding forces and fricBon (e.g., many interesBng cases) … leading to “jerky” behavior 17 Frame Rate Independence • CompleX numerical simulaons used in physics engines are sensiBve to Bme steps (due to truncaon error and other numerical effects) • But results need to be repeatable regardless of CPU/GPU performance – for debugging – for game play • So, if frame rate drops (game loop can’t keep up), then physics will change • Soluon: Control physics simulaon interval independently of frame rate 18 9 4/5/17 Frame Rate Independence delta simula)on )cks lag frame updates previous now start = ... delta = 0.02 // physics simula)on interval (sec) lag = 0 // )me since last simulated previous = 0 // )me of previous call to update function update() { // in game loop now = getTime() t = (previous - start) – lag // previous simulate() lag = lag + (now - previous) // current lag while ( lag > delta ) // repeat un)l caught up t = t + delta simulate(t) lag = lag - delta previous = now // simula)on caught up to current )me } 19 Outline • IntroducBon (done) • Kinemacs (done) • The Firing Soluon (next) • Collision DetecBon • Ragdoll Physics • PhysX 20 10 4/5/17 The Firing Soluon (1 of 3) • How to hit target – Beam weapon or high-velocity bullet over short ranges can be viewed as traveling in straight line – But projecBle travels in parabolic arc • Grenade, spear, catapult, etc. d = ut + at2/2 a = [0, 0, -9.8] m/sec2 (but can use higher value, e.g., -18) d u = velocity vector Most typical game situaons, magnitude of u fixed. We only need to know relave components (orientaon) à Challenge: • Given a, d, solve for u 21 Remember Quadrac Equaons? • Make nice curves – Like firing at target! • SoluBons are where equals 0. E.g., when firing with gun on ground: – At gun muzzle – At target • But unlike in algebra class, not just solving quadrac but finding angle with y = gun, y = target • Angle changes speed in X-direcBon, but also Bme spent in air • Aver hairy math [Millington 3.5.3], three relevant cases: – Target is out of range (no soluBon) • Solve with quadrac formula – Target is at eXact maximum range (single soluon) – Target is closer than maximum range (two possible soluBons) 22 11 4/5/17 The Firing Soluon (2 of 3) long Bme trajectory short Bme trajectory [Millington 3.5.3] u = (2Δ - at2) / (2 (muzzle_v) t) d u = muzzle velocity vector where muzzle_v = max muzzle speed Δ is difference vector from d to u • Usually choose short Bme trajectory a is gravity – Gives target less Bme to escape – Unless shooBng over wall, etc. 23 The Firing Soluon (3 of 3) function firingSolution (start, target, muzzle_v, gravity) { // Calculate vector back from target to start delta = target - start // Real-valued coefficents of quadra)c equa)on a = gravity * gravity b = -4 * (gravity * delta + muzzle_v * muzzle_v) c = 4 * delta * delta // Check for no real solu)ons if ( 4 * a * c > b * b ) return null // Find short and long )mes to target disc = sqrt (b * b - 4 * a *c) Note, a, b and c are scalars t1 = sqrt ( ( -b + disc ) / (2 * a )) so a normal square root. t2 = sqrt ( ( -b - disc ) / (2 * a )) // Pick shortest valid )me to target (t) if ( t1 < 0 ) && ( t2 < 0) return null // No valid )mes if ( t1 < 0 ) ttt = t2 else if ( t2 < 0 ) ttt = t1 else Note scalar product of two vectors using *: ttt = min ( t1, t2 ) [a,b,c] * [d,e,f] = a*d + b*e + c*f // Return firing vector return ( 2 * delta - gravity * ttt * ttt ) / ( 2 * muzzle_v * ttt ) } [Millington 3.5.3] 24 12 4/5/17 Outline • IntroducBon (done) • Kinemacs (done) • The Firing Soluon (done) • Collision DetecBon (next) • Ragdoll Physics • PhysX 25 Collision DetecBon • Determining when objects collide is not as easy as it seems – Geometry can be compleX – Objects can be moving quickly – There can be many objects • naive algorithms are O(n2) • Two basic approaches: – Overlap tesBng • Detects whether collision has already occurred – IntersecBon tesBng • Predicts whether collision will occur in future 26 13 4/5/17 Basics –