Basic Game Physics - WPI

3y ago
33 Views
4 Downloads
2.20 MB
26 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Brenna Zink
Transcription

Basic Game PhysicsTechnical Game Development IIProfessor Charles RichComputer Science Departmentrich@wpi.edu[some material provided by Mark Claypool]IMGD 4000 (D 09)1Introduction What is game physics and why is itimportant? computing motion of objects in virtual scene– including player avatars, NPC’s, inanimate objects computing mechanical interactions of objects– interaction usually involves contact (collision) simulation must be real-time (versus highprecision simulation for CAD/CAM, etc.) simulation may be very realistic, approximate, orintentionally distorted (for effect)IMGD 4000 (D 09)21

Introduction (cont’d) What is game physics and why is itimportant? can improve immersion can support new gameplay elements becoming increasingly prominent (expected) partof high-end games like AI and graphics, facilitated by hardwaredevelopments (multi-core, GPU) maturation of physics engine marketIMGD 4000 (D 09)3Physics Engines Similar buy vs. build analysis as game engines Buy:––––complete solution from day oneproven, robust code base (hopefully)feature sets are pre-definedcosts range from free to expensive Build:––––choose exactly features you wantopportunity for more game-specification optimizationsgreater opportunity to innovatecost guaranteed to be expensive (unless features extremelyminimal)IMGD 4000 (D 09)42

Physics Engines Open source Box2D, Bullet, Chipmunk, JigLib, ODE, OPAL, OpenTissue,PAL, Tokamak, Farseer, Physics2d, Glaze Closed source (limited free distribution) Newton Game Dynamics, Simple Physics Engine, True Axis,PhysX Commercial Havok, nV Physics, Vortex Relation to Game Engines integrated/native, e.g,. C4 pluggable, e.g.,– C4 PhysX– jME ODE (via jME Physics)IMGD 4000 (D 09)5Basic Game Physics Concepts Why? To use an engine effectively, you need tounderstand something about what it’s doing You may need to implement small features orextensions yourself Cf. owning a car without understanding anythingabout how it works Examples kinematics and dynamics projectile motion collision detection and responseIMGD 4000 (D 09)63

Kinematics Study of the motion of objects without takinginto account mass or force Basic quantities: position, time Basic equations:d vtv u atd ut at2/2v2 u2 2adwhere:t - (elapsed) timed - distance (change in position)v - (final) velocity (change in distance per unit time)a - acceleration (change in velocity per unit time)u - (initial) velocity7IMGD 4000 (D 09)Kinematics (cont’d)Prediction Example: If you throw a ball straightup into the air with an initial velocity of 10 m/sec, how high will it go?v 0v2 u2 2addu 10 m/seca -10 m/sec2 (approx due to gravity)v 0 m/sec (at top of flight)0 102 2(-10)dd 5mIMGD 4000 (D 09)a -10u 10(note answer independent of mass of ball)84

Computing Kinematics in Real Timestart getTime() // start timep 0// initial positionu 10// initial velocitya -10function update () { // in render loopnow getTime()t now - startsimulate(t);}function simulate (t) {d (u (0.5 * a * t)) * tmove object to p d}d ut at2/2Problem: Number of calls and time values to simulatedepend on (changing) frame rateIMGD 4000 (D 09)9Frame Rate Independence Complex numerical simulations used in physicsengines are very sensitive to time steps (due totruncation error and other numerical effects) But results need to be repeatable regardless ofCPU/GPU performance for debugging for game play Solution: control simulation interval separatelyIMGD 4000 (D 09)105

Frame Rate Independencedelta 0.02lag 0updated 0// physics simulation interval (sec)// physics lag// time of last updatefunction update () { // in render loopnow getTime()t (updated - start) - laglag lag (now - updated)while ( lag delta )simulate(t)t t deltalag lag - deltaupdated now}simulation ticksdeltalagframe updatesupdatednowIMGD 4000 (D 09)11Doing It In 3D Mathematically, consider all quantitiesinvolving position to be vectors:d vtv u atd ut at2/2(Note these are all scalar products, so essentiallycalculations are performed independently in eachdimension.) Computationally, using appropriate 3-elementvector datatypeIMGD 4000 (D 09)126

The Firing Solution How to hit a target with a grenade, spear, catapult, etc. a beam weapon or high-velocity bullet over shortranges can be viewed as traveling in straight line projectile travels in a parabolic arca [0, 0, -9.8] m/sec2d ut at2/2(but typically use higher value, e.g. -18)u muzzle velocity vectordGiven d, solve for u.IMGD 4000 (D 09)13The Firing Solution In most typical game situation, the magnitudeof u is fixed and we only need to know itsrelative components (orientation) After a lot of hairy math [see Millington 3.5.3], itturns out there are three relevant cases: target is out of range (no solutions) target is at exact maximum range (single solution) target is closer than maximum range (two possiblesolutions)IMGD 4000 (D 09)147

The Firing Solutionlong time trajectoryshort time trajectoryu muzzle velocity vectord Usually choose short time trajectory gives target less time to escape unless shooting over wall, etc.u (2d -at2) / 2xtwhere x max muzzle speedIMGD 4000 (D 09)15function firingSolution (d, x, gravity) {// real-valued coefficents of quadratica gravity * gravityb -4 * (gravity * d x*x)c 4 * d * d// check for no real solutionsif ( 4*a*c b*b ) return null// find short and long timesdisc sqrt(b*b - 4*a*c)t1 sqrt((-b disc) / 2*a)t2 sqrt((-b - disc) / 2*a)if ( t1 0 )if ( t2 0 ) return nullelse t t2else if ( t2 0 ) t t1else t min(t1, t2)// return firing vectorreturn (2*d - gravity*t*t) / (2*x*x)}Note scalar product of two vectors using *, e.g.,[a,b,c] * [d,e,f] a*d b*e c*fIMGD 4000 (D 09)168

Dynamics Notice that the preceding kinematicdescriptions say nothing about why an objectaccelerates (or why its acceleration mightchange) To get a full “modern” physical simulation youneed to add two more basic concepts: force mass Discovered by Sir Isaac Newton around 1700 IMGD 4000 (D 09)17Newton’s Laws1. A body will remain at rest or continue tomove in a straight line at a constant speedunless acted upon by a force.2. The acceleration of a body is proportional tothe resultant force acting on the body and isin the same direction as the resultant force.3. For every action, there is an equal andopposite reaction.IMGD 4000 (D 09)189

Motion Without Newton’s Laws Pac-Man or early Mario style follow path with instantaneous changes in speedand direction (velocity) not physically possible fine for some casual games (esp. with appropriateanimations)IMGD 4000 (D 09)19Newton’s Second LawF maat each moment in time:F force vector, Newton’sm mass (intrinsic property of matter), kga acceleration vector, m/sec2This equation is the fundamental driver of all physics simulations: force causes acceleration acceleration causes change in velocity velocity causes change in positionIMGD 4000 (D 09)2010

How Are Forces Applied? Without contact gravity wind (if not modeling air particles) magic Usually involves contact collision (rebound) friction (rolling, sliding) Dynamic (force) modeling also used forautonomous steering behaviors (later in term)IMGD 4000 (D 09)21Collision Detection Determining when objects collide is not aseasy 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 testing– detects whether collision has already occurred intersection testing– predicts whether a collision will occur in the futureIMGD 4000 (D 09)2211

Overlap Testing Most common technique used in games Exhibits more error than intersection testing Basic idea: at every simulation step, test every pair of objectsto see if overlap Easy for simple volumes (e.g., spheres),harder for polygonal models Results of test: collision normal vector (useful for reaction) time that collision took place23IMGD 4000 (D 09)Overlap Testing: Finding Collision Time Calculated by doing “binary search” in time, movingobject back and forth by 1/2 steps t1BInitial OverlapTestBBIteration 1Forward 1/2Iteration 2Backward 1/4BBIteration 3Forward 1/8Iteration 4Forward 1/16BIteration 5Backward 1/32 In practice, five iterations usually enoughIMGD 4000 (D 09)2412

Limitations of Overlap Testing Fails with objects that move too fast (no overlapduring simulation time slice)windowt-1t0t1t2bullet Solution approach: constrain game design so that fastest object moves smallerdistance in one tick than thinnest object may require reducing simulation step size (adds computationoverhead)25IMGD 4000 (D 09)Intersection Testing Predict future collisions Extrude geometry in direction of movement e.g., “swept” sphere turns into capsule shapet0t1 Then, see if extruded shape overlaps objects When collision found (predicted) move simulation to time of collision (no searching)resolve collisionsimulate remaining time step(s)works for bullet/window exampleIMGD 4000 (D 09)2613

Speeding Up Collision Detection Bounding Volumes Oriented Hierarchical Partitioning Plane Sweep27IMGD 4000 (D 09)Bounding Volumes If bounding volumes don’t overlap, then nomore testing is required if overlap, more refined testing required bounding volume alone may be good enough forsome games Commonly used volumes sphere - distance between centers less than sum of radii boxes– axis aligned (loose fit, easier math)– oriented (tighter fit, more expensive)Axis-Aligned Bounding BoxIMGD 4000 (D 09)Oriented Bounding Box2814

Complex Bounding Volumes Multiple volumes per object e.g., separate volumes for head, torso and limbsof avatar object Hierarchical volumes e.g., boxes inside of boxes Techniques can be combined e.g., hierarchical oriented bounding boxes(OBBTree) in jMEIMGD 4000 (D 09)29Oriented Bounding Box Tree[Gottschalk, Lin, Minocha, SIGGRAPH ’96]IMGD 4000 (D 09)3015

Partitioning for Collision Testing To address the n2 problem. Partition space so only test objects in same cell In best case (uniform distribution) reduces n2 to linear In worst case (all objects in same cell) noimprovement31IMGD 4000 (D 09)Plane Sweep for Collision Testing Observation: a lot of objects stay in one place Sort bounds along axes (expensive to do once!) Only adjacent sorted objects which overlap on allaxes need to be checked further Since many objects don’t move, can keep sort up todate very cheaply with bubblesort (nearly linear)yB1A1R1BAB0RA0C1R0CC0A0IMGD 4000 (D 09)A1 R0B0 R1 C0 B1C1x3216

More physics we are not covering Collision response Conservation of momentum Elastic collisions Non-elastic collisions - coefficient of restitution Rigid body simulation (vs. point masses) Soft body simulation spring-mass-damper dynamics[see excellent recent book by Millington, “Game PhysicsEngine Development”, MK, 2007]IMGD 4000 (D 09)33Open Dynamics Engine Brief case study of a complete physics engine Overview from author (Russell Smith) jME Physics interfaceIMGD 4000 (D 09)3417

IMGD 4000 (D 09)35IMGD 4000 (D 09)3618

IMGD 4000 (D 09)37IMGD 4000 (D 09)3819

IMGD 4000 (D 09)39IMGD 4000 (D 09)4020

IMGD 4000 (D 09)41IMGD 4000 (D 09)4221

IMGD 4000 (D 09)43IMGD 4000 (D 09)4422

IMGD 4000 (D 09)45IMGD 4000 (D 09)4623

IMGD 4000 (D 09)47IMGD 4000 (D 09)4824

49IMGD 4000 (D 09)jME/ODE Integration (jME Physics 2.1)https://jmephysics.dev.java.netIMGD 4000 (D 09)5025

jME Physics (2.1)IMGD 4000 (D 09)5126

Basic Game Physics Technical Game Development II [some material provided by Mark Claypool] IMGD 4000 (D 09) 2 Introduction What is game physics and why is it important? computing motion of objects in virtual scene – including player avatars, NPC’s, inanimate objects computing mechanical interactions of objects

Related Documents:

Iron Angel Force back the invading enemy using a customizable mech-suit. by Brainstorm Productions: Eric Benson erbenson@wpi.edu Keenan Gray krgray@wpi.edu Connor Porell cgporell@wpi.edu . 2!! Game Summary Iron Angel is an exciting action-based shooter. The player is put in control of a powerful mech-

Physics 20 General College Physics (PHYS 104). Camosun College Physics 20 General Elementary Physics (PHYS 20). Medicine Hat College Physics 20 Physics (ASP 114). NAIT Physics 20 Radiology (Z-HO9 A408). Red River College Physics 20 Physics (PHYS 184). Saskatchewan Polytechnic (SIAST) Physics 20 Physics (PHYS 184). Physics (PHYS 182).

Using the WPI Robotics Library The WPI Robotics library (WPILib) is a set of software classes that interfaces with the hardware in your FRC robots control system. There are classes to handle sensors, motors, the driver station, and a number of other utility functions such as timing and field management. What is the WPI Robotics Library?

7 Terminology WPI: Worcester Polytechnic Institute, a four-year private university in Worcester, Massachusetts, USA MQP: Major Qualifying Project, a project done at WPI, usually completed in a student's senior year. It is in the student's major field, and must be completed prior to graduating. [WPI, 2014] CS: Computer Science HTML: Hypertext Markup Language, a markup language that is used .

Advanced Placement Physics 1 and Physics 2 are offered at Fredericton High School in a unique configuration over three 90 h courses. (Previously Physics 111, Physics 121 and AP Physics B 120; will now be called Physics 111, Physics 121 and AP Physics 2 120). The content for AP Physics 1 is divided

(AS OF CLASS OF 2022) WPI was founded on the principle that students learn most effectively by applying theory to practice. WPI has 50 years of experience integrating projects into our undergraduate curriculum. . Phy

Game board printable Game pieces printable Game cards printable Dice Scissors Directions Game Set Up 1. Print and cut out the game board, game pieces, and game cards. 2. Fold the game pieces along the middle line to make them stand up. 3. Place game pieces on the START square. Game Rules 1. Each player take

accounting equation as shown above. The accounting equation is a simple expression of the fact that at any point in time the assets of the entity will be equal to its liabilities plus its equity. The transactions of a new business entity in its first five days are as follows: Required: