Upload
vothu
View
214
Download
1
Embed Size (px)
Citation preview
Physics for JavaScriptGames, Animation, and
Simulations
With HTML5 Canvas
Dev Ramtal
Adrian Dobre
Apress*
Contents at a Glance
J
About the Authors xxi
About the Technical Reviewer xxiii
Acknowledgments xxv
Introduction xxvii
^Part I: The Basics 1
BChapter 1: Introduction to Physics Programming 3
^Chapter 2: JavaScript and HTML5 Canvas Basics......... ....11
IsChapter 3: Some Math Background 37
Chapter 4: Basic Physics Concepts 75
I* Part II: Particles, Forces, and Motion 109
^Chapter 5: The Laws Governing Motion 111
^Chapter 6: Gravity, Orbits, and Rockets 133
^Chapter 7: Contact and Fluid Forces 155
^Chapter 8: Restoring Forces: Springs and Oscillations 187
^Chapter 9: Centripetal Forces: Rotational Motion 209
sChapter 10: Long-Range Forces 233
UPart III: Multi-particle and Extended Systems 265
^Chapter 11: Collisions 267
<3 Chapter 12: Particle Systems 301
81 Chapter 13: Extended Objects 333
V
CONTENTS AT A GLANCE
iiPart IV: Building More Complex Simulations 375
Chapter 14: Numerical Integration Schemes, Accuracy, and Scaling 377
^Chapter 15: Doing Physics in 3D 399
^Chapter 16: Simulation Projects 429
Index 467
vi
Contents
J
About the Authors xxi
About the Technical Reviewer xxiii
Acknowledgments xxv
Introduction xxvii
KPart I: The Basics 1
I Chapter 1: Introduction to Physics Programming 3
Why model real physics? 3
Creating realistic animation effects 3
Creating realistic games 4
Building simulations and models 4
Generating art from code 4
What is physics? 4
Everything behaves according to the laws of physics 5
The laws can be written as math equations 5
Predicting motion 5
Programming physics 6
The difference between animation and simulation 6
The laws of physics are simple equations 6
Equations can be readily coded up! 6
The four steps for programming physics 7
vii
CONTENTS
A simple physics simulation example 7
The physics of a bouncing ball 7
Coding up a bouncing ball in 2D 8
Summary10
HChapter 2: JavaScript and HTML5 Canvas Basics 11
HTML5, the canvas element, and JavaScript 12
A minimal HTML5 document 12
The canvas element 12
Adding JavaScript 13
The JavaScript debugging console 14
JavaScript objects 14
Objects and properties 14
Functions and methods 15
Prototypes, constructors, and inheritance 16
Static properties and methods 17
Example: a Ball object 17
JavaScript frameworks, libraries, and APIs 18
JavaScript language basics 18
Variables 18
Datatypes 19
Operators 21
Math 22
Logic 22
Loops 24
Events and user interaction 26
Event listeners and handlers 26
User interaction: keyboard, mouse, and touch events 26
Drag and drop 27
viii
CONTENTS
The canvas coordinate system 28
The canvas drawing API 28
The canvas context 29
Drawing lines and curves 29
Creating fills and gradients 30
Animating using the canvas context 31
Producing animation using code 31
Using JavaScript timers 32
Using requestAnimationFrameO 32
Using getTimeO to compute elapsed time 34
Precalculating motion 35
Summary 35
^Chapter 3: Some Math Background 37
Coordinates and simple graphs 38
Building a plotter: the Graph object 38
Plotting functions using the Graph object 39
Drawing straight lines 40
Drawing polynomial curves 41
Things that grow and decay, exponential and log functions 42
Making an object move along a curve 43
Finding the distance between two points 48
Basic trigonometry 50
Degrees and radians 50
The sine function 51
The cosine function 52
The tangent function 52
The inverse trig functions 53
Using trig functions for animation 54
Vectors and basic vector algebra 58
What are vectors? 58
Vectors vs. scalars 59
ix
CONTENTS
Adding and subtracting vectors59
Resolving vectors: vector components 60
Multiplying vectors: Scalar or dot product 63
Multiplying vectors:Vector or cross product 64
Building a Vector object with vector algebra 65
Simple calculus ideas 66
Slope of a line: gradient 66
Rates of change: derivatives 67
Doing sums: integrals 72
Summary 73
II Chapter 4: Basic Physics Concepts 75
General physics concepts and notation 75
Physical quantities and units 75
Scientific notation 76
Things: particles and other objects in physics 76
What is a particle? 77
Particle properties 77
Building a Particle object 77
Extending the Particle object 79
Moving particles 82
Describing motion: kinematics 84
Concepts: displacement, velocity, speed, acceleration 84
Combining vector quantities 87
Describing motion using graphs 88
Equations of motion for uniform acceleration 88
Example: Applying the equations to projectile motion 90
More motion-related concepts: inertia, mass, and momentum 93
Predicting motion: forces and dynamics 93
The cause of motion: forces 94
The relationship between force, mass, and acceleration 94
Types of forces 95
x
CONTENTS
Combining forces: force diagrams and resultant force 95
Forces in equilibrium 96
Example: Object falling under gravity and drag 97
Energy concepts 100
The notion of work in physics 101
The capacity to do work: energy 102
Energy transfer, conversion, and conservation 102
Potential and kinetic energy 103
Power 104
Example: A rudimentary "car" simulation 104
Summary 108
MPart II: Particles, Forces, and Motion 109
^Chapter 5: The Laws Governing Motion 111
Newton's laws of motion 111
Newton's first law of motion (N1) 112
Newton's second law of motion (N2) 112
Newton's third law of motion (N3) 113
Applying Newton's laws 114
General method for applying ¥ = ma 114
Coding up motion under any force 115
The Forces object 116
A simple example: projectile with drag 117
A more complicated example: floating ball 119
Newton's second law as a differential equation 122
Taking a deeper look at F = ma 122
Example: Falling under gravity and drag revisited 123
The principle of energy conservation 125
Conservation of mechanical energy 125
Example: Energy changes in a projectile 125
xi
CONTENTS
The principle of momentum conservation 128
Example: 1D elastic collision between two particles 129
Laws governing rotational motion 132
Summary 132
Chapter 6: Gravity, Orbits, and Rockets 133
Gravity 133
Gravity, weight, and mass 133
Newton's universal law of gravitation 134
Creating the gravity function 135
Orbits 136
The orbits code 137
Escape velocity 140
Two-body motion 140
Local gravity 143
The force of gravity near the Earth's surface 143
Variation of gravity with height 145
Gravity on other celestial bodies 146
Rockets 146
It is rocket science! 147
Modeling the thrust of a rocket 147
Building a rocket simulation 147
Summary 153
^Chapter 7: Contact and Fluid Forces 155
Contact forces 155
Normal contact forces 156
Tension and compression 156
Friction157
Example: Sliding down a slope 158
xii
CONTENTS
Pressure 164
The meaning of pressure 164
Density 165
Variation of pressure with depth in a fluid 165
Static and dynamic pressure 166
Upthrust (buoyancy) 166
Archimedes' Principle 167
Apparent weight 167
Submerged objects 168
Floating objects 169
Example: Balloon 169
Drag 170
Drag law for low velocities 170
Drag law for high velocities 171
Which drag law should I use? 172
Adding drag to the balloon simulation 173
Example: Floating ball 173
Terminal velocity 176
Example: Parachute 177
Lift 179
Lift coefficients 180
Example: An airplane 180
Wind and turbulence 182
Force due to the wind 182
Wind and drag 182
Steady and turbulent flow 183
Example: Air bubbles in a steady wind 183
Modeling turbulence 185
Summary 186
xiii
CONTENTS
^Chapter 8: Restoring Forces: Springs and Oscillations 187
Springs and oscillations: Basic concepts 187
Spring-like motion 187
Restoring force, damping, and forcing 188
Hooke's law 188
Free oscillations 189
The spring force function 189
Creating a basic oscillator 190
Simple harmonic motion 191
Oscillations and numerical accuracy 193
Damped oscillations 195
Damping force 195
The effect of damping on oscillations 196
Analytical solutions for oscillations with damping 198
Forced oscillations 198
Driving forces 199
Example: A periodic driving force 199
Example: A random driving force 200
Gravity as a driving force: bungee jumping 201
Example: Driving force by user interaction 204
Coupled oscillators: Multiple springs and objects 205
Example: A chain of objects connected by springs 205
Summary 208
^Chapter 9: Centripetal Forces: Rotational Motion 209
Kinematics of uniform circular motion 209
Angular displacement 209
Angular velocity 210
Angular acceleration 211
Period, frequency, and angular velocity 211
xiv
CONTENTS
The relationship between angular velocity and linear velocity 212
Example: A rolling wheel 213
Example: Satellite around a rotating Earth 216
Centripetal acceleration and centripetal force 218
Centripetal acceleration 218
Centripetal acceleration, velocity, and angular velocity 219
Centripetal force 220
Common misconceptions about centripetal force 220
Example: Revisiting the satellite animation 221
Example: Circular orbits with gravitational force 222
Example: Car moving around a bend 224
Non-uniform circular motion 228
Tangential force and acceleration 228
Example: A simple pendulum 228
Summary 232
HChapter 10: Long-Range Forces 233
Particle interactions and force fields 233
Interaction at a distance 233
From particle interactions to force fields 234
Newtonian gravitation 234
Gravitational field due to a particle 235
Gravity with multiple orbiters 235
Gravity with multiple attractors 237
Particle trajectories in a gravity field 239
Building a simple black hole game 242
Electrostatic force 247
Electric charge 247
Coulomb's law of electrostatics 248
Charged particle attraction and repulsion 248
Electric fields 250
XV
CONTENTS
Electromagnetic force 253
Magnetic fields and forces 254
The Lorentz force law 255
Other force laws 256
Central forces 256
Gravity with a spring force law? 259
Multiple attractors with different laws of gravity 261
Summary 263
SPart III: Multi-particle and Extended Systems 265
^Chapter 11: Collisions 267
Collisions and their modeling 267
Bouncing off horizontal or vertical walls 268
Elastic bouncing 268
Inelastic bouncing 272
Bouncing off inclined walls 272
Collision detection with an inclined wall 273
Repositioning the particle 274
Calculating the new velocity 275
Velocity correction just before collision 277
Example: a ball bouncing off an inclined wall 278
Example: Ball bouncing off multiple inclined walls 283
Collisions between particles in 1D 284
Repositioning the particles 284
Elastic collisions 287
Inelastic collisions 290
Collisions between particles in 2D 291
Example: 2D collisions between two particles 292
Example: multiple particle collisions 295
Example: multiple particle collisions with bouncing 296
Summary 299
xvi
CONTENTS
& Chapter 12: Particle Systems 301
Introduction to particle system modeling 301
Creating animated effects using particles 302
A simple example: splash effect with particles 302
Creating a particle emitter 306
Creating a smoke effect 309
Creating a fire effect 312
Creating fireworks 314
Particle animations with long-range forces 319
Particle paths in a force field 319
Building a wormhole 322
Interacting particle systems 324
Multiple particles under mutual gravity 324
A simple galaxy simulation 327
Summary 332
Chapter 13: Extended Objects 333
Rigid bodies 333
Basic concepts of rigid body modeling 333
Modeling rigid bodies 341
Rotational dynamics of rigid bodies 343
Simulating rigid body dynamics 346
Example: a simple wind turbine simulation 349
Example: Rolling down an inclined plane 351
Rigid body collisions and bouncing 357
Example: Simulating a single bouncing block 360
Example: Colliding blocks 363
Deformable bodies 365
Mass-spring systems 365
Rope simulation 367
Cloth simulation 371
Summary 373
xvii
CONTENTS
IPart IV: Building More Complex Simulations 375
5!Chapter 14: Numerical Integration Schemes, Accuracy, and Scaling 377
General principles 378
Statement of the problem 378
Characteristics of numerical schemes 380
Types of integration schemes 381
A simple example to demonstrate different integration schemes 382
Euler integration 383
Explicit Euler 384
Implicit Euler 384
Semi-implicit Euler 385
Comparing the explicit and semi-implicit Euler schemes 385
Why use Euler and why not? 386
Runge-Kutta integration 386
Second-order Runge-Kutta scheme (RK2) 387
Fourth-order Runge-Kutta scheme (RK4) 388
Stability and accuracy of RK2 and RK4 compared with Euler 389
Verlet integration 390
The Position Verlet Method 390
The Velocity Verlet Method 392
Testing the stability and accuracy of the Verlet schemes 392
Tips for achieving accuracy 393
Choosing an appropriate integration scheme 393
Using an appropriate timestep 393
Using accurate initial conditions 394
Dealing with boundaries carefully 394
Building scale models 394
Scaling for realism 394
A simple example 395
xviii
CONTENTS
Choosing units 395
Scaling factors and parameter values 396
Rescaling equations 396
Summary 397
^Chapter 15: Doing Physics in 3D 399
3D physics and math 399
3D versus 2D physics 399
Vectors in 3D 400
Forces in 3D 402
Matrices and rotation 404
Quaternions 407
Rotational dynamics in 3D 409
3D rendering: Introducing WebGL and three.js 410
Canvas, WebGL, and WebGL frameworks 410
A quick three.js primer 411
Simulating particle motion in 3D 413
A bouncing ball simulation in 3D 414
A rotating Earth animation 416
Forces: gravity and orbits in 3D 418
Simulating rigid body motion in 3D 421
A rotating cube animation 421
Applying a force to the rotating cube 423
Rotating the cube about an arbitrary axis 426
Summary 428
Chapter 16: Simulation Projects 429
Building a submarine 429
Brief review of the physics 429
The visual setup 430
The setup code 431
The basic motion code 432
xix
CONTENTS
Adding controls and visual effects 432
The full code 434
It's your turn 437
Building a flight simulator 437
Physics and control mechanisms of aircraft 437
What we will create 442
Creating the visual setup 442
Coding up the physics 444
Implementing the controls 447
Displaying flight information 447
Test flying the simulator 448
It's your turn 448
Creating an accurate solar system model 449
What we will create 449
The physics 449
Coding up an appropriate integration scheme 450
Building an idealized single-planet simulation 452
Choosing appropriate scaling factors 454
Obtaining planetary data and initial conditions 455
Creating a basic solar system model 456
Incorporating accurate initial conditions 461
Comparing the model results with NASA data 462
Animating the solar system simulation 464
It's your turn 465
Summary 465
Index 467
XX