ebook img

Physics for JavaScript Games, Animation, and Simulations PDF

490 Pages·2014·11.72 MB·English
by  
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Physics for JavaScript Games, Animation, and Simulations

BOOKS FOR PROFESSIONALS BY PROFESSIONALS® Ramtal Dobre Physics for JavaScript Games, RELATED Animation, and Simulations Have you ever wanted to include believable physical behaviors in your games and projects to give them that extra edge? Physics for JavaScript Games, Animation, and Simulations teaches you how to incorporate real physics, such as gravity, friction, and buoyancy, into your HTML5 games, animations, and simulations. It also includes more advanced topics, such as particle systems, which are essential for creating effects such as sparks or smoke. The book also addresses the key issue of balancing accuracy and simplicity in your games and simulations, and the final chapters provide you with the information and the code to make the right choice for your project. Physics for JavaScript Games, Animation, and Simulations assumes you have a basic knowledge of JavaScript and HTML5. However, no previous knowledge of physics is required—only some very basic math skills. The authors present everything from basic principles to advanced concepts in an approachable way, so you’ll be able to follow the logic and easily adapt the principles to your own applications. The book is packed full of practical examples of how you can apply physics to your own games and applications. Spring behaviors can be used for anything from tweaking lowrider suspension to creating cloth simulation; flotation mechanics enable the simulation of submersibles or dirigibles; you can even create your own solar system with accurate orbits and gravity. It doesn’t matter if you’re modeling the Lorentz force in an electromagnetic field or you’re modeling the lift force in a flight simulator, Physics for JavaScript Games, Animation, and Simulations enables you to fill your games and applications with accurate and realistic effects. In this book you’ll: • Learn all the basic math and physics you’ll need to incorporate realism into your projects • Incorporate a wide range of forces, such as gravity, friction, and buoyancy • Build a number of realistic simulations • Model particle systems and use them to create visual effects • Create complex systems using rigid bodies and mass-spring systems • Deal with numerical subtleties, including accuracy and stability of integration schemes Physics for JavaScript Games, Animation, and Simulations is for JavaScript developers interested in incorporating real physics into their games, animations, simulations, or generative art projects. Shelve in ISBN 978-1-4302-6337-1 Web Development/JavaScript 54999 User level: Intermediate–Advanced SOURCE CODE ONLINE 9781430263371 www.apress.com For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. Contents at a Glance About the Authors ��������������������������������������������������������������������������������������������������������������xxi About the Technical Reviewer �����������������������������������������������������������������������������������������xxiii Acknowledgments ������������������������������������������������������������������������������������������������������������xxv Introduction ��������������������������������������������������������������������������������������������������������������������xxvii ■ Part I: The Basics ������������������������������������������������������������������������������������������1 ■ Chapter 1: Introduction to Physics Programming �������������������������������������������������������������3 ■ Chapter 2: JavaScript and HTML5 Canvas Basics �����������������������������������������������������������11 ■ Chapter 3: Some Math Background ���������������������������������������������������������������������������������37 ■ Chapter 4: Basic Physics Concepts ���������������������������������������������������������������������������������75 ■ 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 ■ Chapter 10: Long-Range Forces ������������������������������������������������������������������������������������233 ■ Part III: Multi-particle and Extended Systems ������������������������������������������265 ■ Chapter 11: Collisions����������������������������������������������������������������������������������������������������267 ■ Chapter 12: Particle Systems ����������������������������������������������������������������������������������������301 ■ Chapter 13: Extended Objects ���������������������������������������������������������������������������������������333 v ■ Contents at a GlanCe ■ Part 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 Introduction We hope you will enjoy reading—and using—this book as much as we enjoyed writing it. Creating physics-based simulations is a lot of fun—there is great satisfaction in writing a few lines of code and then seeing them bring inanimate objects to life, behaving as they do in the real world! This is a striking demonstration that the natural world is governed by simple laws, and that we have at least an approximate grasp of those laws. The ability to replicate the real world in a computer program gives us great power as programmers. The aim of this book is to provide you with tools that will make you feel that awesome sense of power. Whether you want to build convincing animations, games that behave realistically, or accurate simulators, you will find herein plenty of tools, examples, and ideas that should be of help. This book is based closely on our earlier book, Physics for Flash Games, Animation, and Simulations (Apress, 2011). Although the physics content has not changed, the numerous examples in the book have been rewritten from scratch in JavaScript for rendering in an HTML5 canvas. The last two chapters also include some WebGL examples, with the help of the three.js JavaScript library. All the examples are designed for use in a web browser. Although we don’t give any examples of mobile apps, the examples given can be easily adapted for mobile devices. While the popularity of JavaScript is on the rise, there is currently a lack of resources for creating physics-based animation using JavaScript. The excellent book by Billy Lamberta and Keith Peters, Foundation HTML5 Animation with JavaScript (Apress, 2011), contains good coverage of physics-related topics and provides a great introduction to the subject. It seemed to us that there was also a need for a book that explored physics further and in greater depth, and that catered to more demanding applications such as accurate simulators or more complex game programming. After all, there are several “game physics” books written for other programming languages, such as C++ and Java, so why not JavaScript? This book is meant to fill that gap. We should make it clear at the outset that this is primarily a book about applying physics to your coding projects; hence we tend to focus less on producing attractive visual effects and more on modeling real physics. Some of the animations in the book may not be very pretty or smooth from a visual perspective, but they do contain a lot of physics you can apply! By the same token, there is little emphasis on writing elegant code—rather we prefer to keep the coding simple and clean, so that the physics content may not be obscured by over-clever programming. The approach we adopt attempts to make serious physics accessible. But although we don’t shy away from going into technical information, with all of the accompanying math, we hope to have done so in a way that is simple and straightforward. Inevitably, because of space and time restrictions, there are topics that we were not able to include or that we didn’t explore in detail. Nevertheless, the book covers an awful lot of ground, taking you from coding a simple bouncing ball animation in a few lines of code in the first chapter to a highly accurate simulation of the solar system in the final chapter. We hope you enjoy the journey in between! What this book will (and won’t) teach you Physics for JavaScript Games, Animation, and Simulations teaches you how to incorporate physics into your programming. It does not teach you how to program. It does not teach you JavaScript. We assume that you have at least some programming experience, preferably with JavaScript (or a similar programming language). And although this book teaches you how to implement physics into your games (as well as other projects), it is not about game programming per se. xxvii ■ IntroduCtIon We do not assume any previous knowledge of physics, and we assume only basic school-level math knowledge. One chapter is dedicated to explaining some of the more difficult math concepts and tools that you are likely to need in the book. All the physics concepts and knowledge you will need are explained in a self-contained way. Numerous applications are given throughout the book with full source code to illustrate the application of the principles learned. Overview of this book This book is divided into four parts: Part I: “The Basics” (Chapters 1–4) introduces the necessary background in basic math and physics concepts upon which the rest of the book builds. For completeness, it also covers selected topics in JavaScript that are most pertinent to physics programming. Part II: “Particles, Forces, and Motion” (Chapters 5–10) begins by formulating the laws of physics that govern the motion of particles under any type of force (Chapter 5). The next five chapters then apply those laws to make objects move under the action of a variety of forces including gravity, friction, drag, buoyancy, wind, springs, central forces, and many more. The main focus in this section is on simulating the motion of individual particles and other simple objects. In Part III: “Multi-Particle and Extended Systems” (Chapters 11–13), we show you how to model more complicated systems, including multiple interacting particles and extended objects. In these systems the constituent particles and objects may not simply co-exist but also interact with one another, mutually influencing their motion. These interactions include collisions, short-range forces, and long-range forces. This part includes a discussion of particle systems, rigid bodies, and deformable bodies. Part IV: “Building More Complex Simulations” (Chapters 14–16) is devoted to building more complex simulations, where accuracy and/or realism is especially important, not just visual effects. This part includes a discussion of integration schemes and other numerical and technical issues such as scale modeling and 3D. Part IV ends with a chapter that includes some example simulation projects, which the reader is encouraged to build upon. Source code and examples All the code for this book can be downloaded from the book’s page on the Apress website: www.apress.com. An up-to-date version of the code will also be maintained on github.com. We encourage you to modify and build upon the example codes given. We also invite you to share your codes, and have set up the following page on our website where you can find and contribute more code and examples: www.physicscodes.com/jsbook. xxviii Part i The Basics Chapter 1 Introduction to Physics Programming You’ve picked up this book because you are interested in implementing physics in your programming projects. But why would you want to do that? What can it do for you? And how difficult will it be? This chapter will provide answers to these questions. Topics covered in this chapter include the following: • Why model real physics? This section will explain some of the reasons why you might want to add physics to your projects. • What is physics? Here we lift the veil of mystery and explain in simple terms what physics is. We also tell you, in a nutshell, what you’ll need to know before you can write code involving physics. • Programming physics. Thankfully, programming physics is not as difficult as you might imagine, once you understand some basic principles. This section explains what you’ll need to do. • A simple example. As a concrete example, we’ll code up a simple animation involving physics, using a minimum of code. Why model real physics? There are a number of reasons why you might be interested in modeling physics using JavaScript. Here are some of the most common: • To create realistic animation effects • To create realistic games • To build simulations and models • To generate art from code Let us look at each in turn. Creating realistic animation effects Thanks to the HTML5 canvas element, it is now possible to create animations without the need for plug-ins such as Flash. With a little JavaScript and some familiarity with physics, it is also possible to make animations that look and behave like the real thing. For example, suppose you are animating a scene in which someone kicks a ball and it bounces off the ground. You could try to create an animation that mimics the ball’s behavior, but however hard you might try, it would probably look less than realistic. With just a little bit of coding and some knowledge of 3 Chapter 1 ■ IntroduCtIon to physICs programmIng elementary physics, you could produce a far more realistic animation. And if, like the authors, you are programmers rather than designers, you might even find it easier! We’ll show you just how easy it can be in the example at the end of this chapter. Creating realistic games Web-based games are extremely popular. As the capabilities of modern web browsers continue to improve, better and more powerful games can be built. Hardware acceleration and 3D support are just two of the emerging developments that have the potential to improve the online gaming user experience dramatically. But apart from performance and appearance, it is equally important for games to feel and look realistic. If a player throws a ball, it should fall according to the law of gravity; if a player fires a torpedo underwater, it should move differently from a ball falling in air. In other words, your game needs to incorporate real physics. How do you build physics awareness into your games? This book will show you how. Building simulations and models A computer simulation or computer model is a program that attempts to imitate certain key aspects of a physical system. Simulations vary in completeness or accuracy, depending on purpose and resources. Let’s take a flight simulator program as an example. We would expect a flight simulator designed for training pilots to be much more comprehensive and accurate than one designed for a game. Simulations are extremely common in e-learning, training, and scientific research. In the final chapter of this book, you’ll build simulations—namely a submarine, a basic flight simulator, and a model of the solar system. In fact, many of the coded examples throughout the book are simulations, even if generally simpler. Generating art from code Generative art has gained popularity in recent years. A lot of fun can be had with some basic physics—for example, elaborate visual effects and motions can be produced using particles (small graphic objects that you can create and animate with code) and different kinds of forces. These effects can include realistic-looking animation such as smoke and fire, as well as more abstract examples of generative art that can be created using a mixture of algorithms, randomness, and user interaction. Adding some physics in the mix can result in enhanced realism and/or richer effects. We will explore the world of generative art and provide additional tools and algorithms that can be used to create original and interesting effects such as particle trajectories in complex force fields. What is physics? Physics is the most fundamental of the sciences. In a broad sense, physics is the study of the natural laws that govern how things behave. More specifically, it concerns itself with space, time, and matter (defined as any “stuff” that exists in space and time). One aspect of physics is to formulate general laws that govern the behavior of matter, its interactions, and its motion in space and time. Another aspect is to use these laws to predict the way specific things move and interact—for example, the prediction of eclipses from the laws of gravity or how airplanes are able to fly from the laws of aerodynamics. Physics is a vast subject, and in a book of this nature we cannot do more than scratch the surface. Fortunately, most of the physics that you will probably need to know falls within a branch known as mechanics, which is one of the easiest to understand. Mechanics governs the way in which objects move and how that motion is influenced by effects in the environment. Because most games and animations include motion, mechanics is clearly of relevance in developing algorithms for making objects behave realistically in code. 4 Chapter 1 ■ IntroduCtIon to physICs programmIng Everything behaves according to the laws of physics Without getting too philosophical, it is fair to say that the laws of physics are truly universal, as far as physicists have been able to observe. What this means is that everything must behave according to physics. This is different from say, the laws of biology, which pertain only to living things. A stone thrown in the air, a planet orbiting the Sun, the workings of the human body, and the operation and motion of a man-made machine must all obey the laws of physics. Moreover, many seemingly diverse phenomena are governed by the same subset of laws. In other words, a single law or group of laws can explain many types of observed facts or patterns of behavior in the physical world. For example, a falling stone and a planet orbiting the Sun both obey the laws of gravity. Another example is that all electrical, magnetic, and radiation phenomena (such as light and radio waves) are governed by the laws of electromagnetism. The laws can be written as math equations The great thing is that the laws of physics can be written as mathematical equations. Okay, that may not sound too great if you don’t like math! But the point here is that for a law to be useful, it has to be made precise. And math equations are as precise as anything can be. There is no possible ambiguity in how to apply a law that is expressed mathematically, in contrast with the laws that are fought over in courtrooms! Second, this means that centuries of developments in mathematics prove to be applicable to physics, making it possible to solve many physics problems. Third, and what is of most relevance for us: math equations are readily convertible into code. Predicting motion Let’s get more specific. As a JavaScript programmer, you are mostly interested in how things move. Much of physics deals with how things move under the action of different types of influences. These “influences” can be from other things and from the environment. Examples include gravity, friction, and air resistance. In physics we have a special name for these influences: they are called forces. The really good news is that the forces have precise mathematical forms. Although the motion of objects is usually complicated, the underlying mathematical laws that describe the forces are usually quite simple. The general relationship between force and motion can be written symbolically as follows: motion = function{forces} Here the use of the word function is not intended to represent an actual code function. Rather, it is meant to emphasize two things. First, it signifies a cause-and-effect relationship. Forces cause objects to move in different ways. Second, it also points to an algorithmic relationship between forces and motion in code, in that the motion of an object can be seen as the output of a function with forces as input. In practical terms, it means this: specify the forces acting on an object and put them in a mathematical equation, and then you can calculate the motion of the object. ■ Note motion is effect. Force is cause. the motion of an object is the result of the forces acting on it. the mathematical relationship between force and motion is known as the “Law of motion.” To be able to put the principle stated in this note to use, you need to know the following: • Definitions. The precise definitions of motion and force. • The law of motion. In other words, the precise mathematical form of the function that relates a force to the motion it produces. • Force laws. In other words, how to calculate the forces. There are equations that tell you how to calculate each type of force. 5

Description:
Physics for JavaScript Games, Animation, and Simulations. With HTML5 Canvas Chapter. Pages 11-35. JavaScript and HTML5 Canvas Basics.
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.