Series Introduction
Perhaps Sir Isaac Newton (Sir Issac Newton, three hundred-1643), 1727 years ago, has not imagined that physics is widely used in many games and animations today. Why should physics be used in these applications? I believe that since we were born, we have been feeling the laws of the physical world, realizing how objects are "moving normally" in this world ", for example, when the ball is shot, the ball is parabolic (the Spin Ball may be made into a arc ball), and the stones will swing at the end of a line at a fixed frequency. To make the objects in a game or animation realistic, the Movement method must meet our expectation for "normal movement.
Today's game animation uses a variety of physical simulation technologies, such as kinematics simulation, rigid body dynamics simulation, and string/cloth simulation) soft body dynamics simulation, fluid dynamics simulation, and so on. In addition, collision detection is required in many simulation systems.
This series hopes to introduce some of the most basic knowledge in this area. We will continue to use JavaScript as an example to experience it through real-time interaction.
Introduction
As the first article in the series, this article describes the simplest kinematics simulation, with only two very simple formulas. Kinematics Simulation can be used to simulate the movement of many objects (such as Mario's jump and shells). This article will work with the particle system to make some visual effects (the particle system can also be used to play games, instead of visual effects ).
Kinematics Simulation
Kinematics is different from dynamics in studying the movement of an object in that the kinematics does not consider the mass of the object (mass)/the moment of inertia (Moment of Inertia ), and does not consider the force and torque of an object ).
Let's first recall Newton's first law of motion:
When the object is not affected by external force, or when the force is zero, the original static is constant static, and the original motion is constant moving along a straight line. This law is also known as the Law of inertia 」. This law states that each object has a linear speed (linear velocity) State in addition to its position. However, it is not interesting to simulate only objects without force impact. Linear acceleration can be used to influence the motion of an object. For example, to calculate the Y axis coordinate of a free falling body at any time t, you can use the following analytical solution ):
Where, and are the start coordinates and velocity of the Y axis when T = 0, while G is the acceleration of gravity (gravitational acceleration ).
This analysis solution is simple, but has some disadvantages. For example, G is a constant and cannot be changed during simulation. In addition, when an object encounters an obstacle and produces a collision, this formula also makes it difficult to deal with such discontinuity ).
In computer simulation, it is usually necessary to calculate the state of consecutive objects. In terms of games, the state of the first frame and the state of the second frame are calculated. Set the state of an object at any time T: position vector, velocity vector, and acceleration vector. We want to calculate the status of the next simulation time from the time state. The simplest method is to use the Euler method for numerical integration ):
The Euler's method is very simple, but there are problems with accuracy and stability. This article will ignore these problems first. The example in this article uses two-dimensional space. We first implement a javascript two-dimensional Vector class:
CopyCode The Code is as follows: // vector2.js
Vector2 = function (x, y) {This. x = x; this. Y = y ;};
Vector2.prototype = {
Copy: function () {return New vector2 (this. X, this. Y );},
Length: function () {return math. SQRT (this. x * This. x + this. y * This. Y );},
Sqrlength: function () {return this. x * This. x + this. y * This. Y ;},
Normalize: function () {var inv = 1/This. Length (); return New vector2 (this. x * inv, this. y * INV );},
Negate: function () {return New vector2 (-This. X,-This. Y );},
Add: function (v) {return New vector2 (this. x + v. X, this. Y + v. Y );},
Subtract: function (v) {return New vector2 (this. X-V. X, this. Y-V. Y );},
Multiply: function (f) {return New vector2 (this. x * F, this. y * f );},
Divide: function (f) {var invf = 1/F; return New vector2 (this. x * invf, this. y * invf );},
Dot: function (v) {return this. x * v. x + this. y * v. Y ;}
};
Vector2.zero = new vector2 (0, 0 );
then, you can use HTML5 canvas to describe the simulated process: copy Code the code is as follows: var position = new vector2 (10,200);
var velocity = new vector2 (50, -50);
var acceleration = new vector2 (0, 10);
var dt = 0.1;
function step () {
position = position. add (velocity. multiply (DT);
velocity = velocity. add (acceleration. multiply (DT);
CTX. strokestyle = "#000000";
CTX. fillstyle = "# ffffff";
CTX. beginpath ();
CTX. ARC (position. x, position. y, 5, 0, math. pI * 2, true);
CTX. closepath ();
CTX. fill ();
CTX. stroke ();
}< br> Start ("kinematicscancas", step);
<Button onclick = "eval (document. getelementbyid ('kinematicscode'). Value)" type = "button"> RUN </button>
<Button onclick = "Stop ();" type = "button"> stop </button>
<Button onclick = "clearcanvas ();" type = "button"> clear </button>
<Table border = "0" style = "width: 100%;">
<Tbody>
<Tr>
<TD> <canvas id = "kinematicscancas" width = "400" Height = "400"> </canvas> </TD>
<TD width = "10"> </TD>
& Lt; TD width = "100%" valign = "TOP" & gt;
<H4> try to modify the code </H4>
<Li> change the starting position </LI>
<Li> change the start speed (including the direction) </LI>
<Li> change acceleration </LI>
</TD>
</Tr>
</Tbody>
</Table>
ThisProgramThe core of the step () function is the first two lines of code. Is it easy?
Particle System
Particle System is a special effect commonly used in graphics. The particle system can apply kinematics simulation to achieve many different effects. In games and animations, particle systems are often used for different visual effects such as rain, Sparks, smoke, and explosion. Sometimes, some gameplay-related functions will also be made. For example, after an enemy is defeated, it will emit some flashes, and the protagonist can absorb them.
Particle Definition
Particle systems simulate a large number of particles and usually use some methods to render the particles. Particles generally have the following features:
<Li> particles are independent, and they do not affect each other (no collision or force) </LI>
<Li> the lifecycle of a particle disappears after the lifecycle ends. </LI>
<Li> A particle can be understood as a point in space, and sometimes a radius can be set as a sphere and an environment collision </LI>
<Li> particles are in motion and other appearance states (such as colors and images) </LI>
<Li> the particle can only perform linear motion without considering the rotation motion (or exceptions) </LI>
The following is the particle class implemented in this example:Copy codeThe Code is as follows: // particle. js
Particle = function (position, velocity, life, color, size ){
This. Position = position;
This. velocity = velocity;
This. Acceleration = vector2.zero;
This. Age = 0;
This. Life = life;
This. Color = color;
This. size = size;
};
game loop
particle systems can generally be divided into three cycles:
particle emission
simulated particles (particle aging, collision, kinematics simulation, etc)
rendering particles
in game loop, you must perform the preceding three steps for each particle system.
Life and Death
in this example, a JavaScript array is used to store all living particles. To generate a particle, add it to the end of the array. The code snippet is as follows: copy Code the code is as follows: // particle system. JS
function participant system () {
// Private fields
var that = This;
var participant = new array ();
// public fields
This. gravity = new vector2 (0,100);
This. tors = new array ();
// public methods
This. emit = function (particle) {
Participant. push (particle);
};
//...
}
when a particle is initialized, age is set to zero, and life is fixed. The unit of age and life is second. In each simulated step, the particle ages, that is, the age is increased by \ delta T . If the age exceeds life, the particle dies. The code snippet is as follows: copy Code the code is as follows: function Particle System () {
//...
This. simulate = function (DT) {
aging (DT);
applygravity ();
applyeffectors ();
kinematics (DT );
};
//...
// Private methods
function aging (DT) {
for (VAR I = 0; I var P = participant [I];
P. age + = DT;
If (P. age> = P. life)
kill (I);
else
I ++;
}< BR >}< br> function kill (INDEX) {
If (participant. length> 1)
Participant [Index] = participant [participant. length-1];
Participant. pop ();
}< br> //...
}
A technique is used in the kill () function. Because the order of particles in the array is not important, to delete a particle in the middle, you only need to copy the last particle to that element and use Pop () to remove the last particle. This is usually faster than directly deleting the elements in the middle of the array (using arrays or STD: vector in C ++ is also ).
kinematics simulation
apply the two most important pieces of kinematics simulation code in this article to all particles. In addition, each simulation first writes the gravity acceleration into the particle's acceleration. This is done to change the acceleration every time in the future (this is part of the continued talks ). copy Code the code is as follows: function participant system () {
//...
function applygravity () {
for (var I in participant)
Participant [I]. acceleration = That. gravity;
}< br> function kinematics (DT) {
for (var I in participant) {
var P = participant [I];
P. position = P. position. add (P. velocity. multiply (DT);
P. velocity = P. velocity. add (P. acceleration. multiply (DT);
}< BR >}< br> //...
}
rendering
particles can be rendered in many different ways, such as circles, line segments (current and previous positions), images, and genie. This article uses a circle and controls the transparency of the circle based on the ratio of age to life. The code snippet is as follows: copy Code the code is as follows: function participant system () {
//...
This. render = function (CTX) {
for (var I in participant) {
var P = participant [I];
var alpha = 1-P. age/P. life;
CTX. fillstyle = "rgba ("
+ math. floor (P. color. R * 255) + ","
+ math. floor (P. color. g * 255) + ","
+ math. floor (P. color. B * 255) + ","
+ Alpha. tofixed (2) + ")";
CTX. beginpath ();
CTX. ARC (P. position. x, p. position. y, P. size, 0, math. pI * 2, true);
CTX. closepath ();
CTX. fill ();
}< BR >}< br> //...
}
completion of the basic Particle System
In the following example, each frame emits a particle located in the middle of the canvas (200,200). The emission direction is 360 degrees and the speed is 100, life is 1 second, Red, radius is 5 pixels. copy Code the code is as follows: vaR PS = new participant system ();
var dt = 0.01;
function sampledirection () {
var Theta = math. random () * 2 * Math. pi;
return New vector2 (math. cos (theta), math. sin (theta);
}< br> function step () {
ps. emit (new particle (New vector2 (200,200), sampledirection (). multiply (100), 1, color. red, 5);
ps. simulate (DT);
clearcanvas ();
ps. render (CTX);
}< br> Start ("basicparticipant lesystemcanvas", step);
<Button onclick = "eval (document. getelementbyid ('basicdetailsystemcode'). Value)" type = "button"> RUN </button>
<Button onclick = "Stop ();" type = "button"> stop </button>
<Table border = "0" style = "width: 100%;">
<Tbody>
<Tr>
<TD> <canvas id = "basicparticipant lesystemcanvas" width = "400" Height = "400"> </canvas> </TD>
<TD width = "10"> </TD>
& Lt; TD width = "100%" valign = "TOP" & gt;
<H4> try to modify the code </H4>
<Li> change the launch position </LI>
<Li> up-launch, with a launch range of 90 degrees </LI>
<Li> change life </LI>
<Li> change radius </LI>
<Li> five particles are emitted each frame </LI>
</TD>
</Tr>
</Tbody>
</Table>
Simple collision
In order to describe the advantages of using numerical integral to the analytical solution, a simple collision is added to the particle system. We want to add a requirement that when a particle encounters the inner wall of a rectangular room (which can be set to the entire canvas size), it will crash and rebound, and the collision is completely elastic (perfectly elastic collision ).
In programming, I use the callback method for this function. The particle system class has an array of variables. Before performing a kinematics simulation, run the apply () function for each of the variables object:
The rectangular room is implemented as follows:Copy codeThe Code is as follows: // chamberbox. js
Function chamberbox (x1, Y1, X2, Y2 ){
This. Apply = function (particle ){
If (particle. position. X-particle. Size <X1 | particle. position. x + particle. size> x2)
Particle. Velocity. x =-particle. Velocity. X;
If (particle. position. Y-particle. Size <Y1 | particle. position. Y + particle. size> Y2)
Particle. Velocity. Y =-particle. Velocity. Y;
};
}
This is actually when we detect that the particle is out of the inner wall, we will reverse the velocity component in this direction.
In addition, the main loop in this example no longer clears the entire canvas each time, but draws a translucent black rectangle each frame to simulate the effect of Dynamic Fuzzy motion (motion blur. The color of the particle is also randomly sampled from two colors. Copy code The Code is as follows: var PS = new participant system ();
PS. schedultors. Push (New chamberbox (0, 0,400,400); // The most important thing is that this statement is added.
VaR dt = 0.01;
Function sampledirection (angle1, angle2 ){
VaR T = math. Random ();
VaR Theta = angle1 * t + angle2 * (1-t );
Return new vector2 (math. Cos (theta), math. Sin (theta ));
}
Function samplecolor (color1, color2 ){
VaR T = math. Random ();
Return color1.multiply (T). Add (color2.multiply (1-t ));
}
Function step (){
PS. emit (new particle (New vector2 (200,200), sampledirection (math. pI * 1.75, math. pI * 2 ). multiply (250), 3, samplecolor (color. blue, color. purple), 5 ));
PS. Simulate (DT );
CTX. fillstyle = "rgba (0, 0, zero, 0.1 )";
CTX. fillrect (0, 0, canvas. Width, canvas. Height );
PS. Render (CTX );
}
Start ("collisionchambercanvas", step );
<Button onclick = "eval (document. getelementbyid ('collisionchambercode'). Value)" type = "button"> RUN </button>
<Button onclick = "Stop ();" type = "button"> stop </button>
<Canvas id = "collisionchambercanvas" width = "400" Height = "400"> </canvas>
Interactive launch
In the last example, the interaction function is added to emit particles at the mouse position. The direction of the particles is to move at the speed of the mouse with a little noise (Noise ). The particle size and life are both random.Copy code The Code is as follows: var PS = new participant system ();
PS. schedultors. Push (New chamberbox (0, 0,400,400 ));
VaR dt = 0.01;
VaR oldmouseposition = vector2.zero, newmouseposition = vector2.zero;
Function sampledirection (angle1, angle2 ){
VaR T = math. Random ();
VaR Theta = angle1 * t + angle2 * (1-t );
Return new vector2 (math. Cos (theta), math. Sin (theta ));
}
Function samplecolor (color1, color2 ){
VaR T = math. Random ();
Return color1.multiply (T). Add (color2.multiply (1-t ));
}
Function samplenumber (value1, value2 ){
VaR T = math. Random ();
Return value1 * t + value2 * (1-t );
}
Function step (){
VaR velocity = newmouseposition. Subtract (oldmouseposition). Multiply (10 );
Velocity = velocity. Add (sampledirection (0, math. Pi * 2). Multiply (20 ));
VaR color = samplecolor (color. Red, color. Yellow );
VaR life = samplenumber (1, 2 );
VaR size = samplenumber (2, 4 );
PS. emit (new particle (newmouseposition, velocity, life, color, size ));
Oldmouseposition = newmouseposition;
PS. Simulate (DT );
CTX. fillstyle = "rgba (0, 0, zero, 0.1 )";
CTX. fillrect (0, 0, canvas. Width, canvas. Height );
PS. Render (CTX );
}
Start ("interactiveemitcanvas", step );
Canvas. onmousemove = function (e ){
If (E. layerx | E. layerx = 0) {// Firefox
E.tar get. style. Position = 'relative ';
Newmouseposition = new vector2 (E. layerx, E. layery );
}
Else
Newmouseposition = new vector2 (E. offsetx, E. offsety );
};
<Button onclick = "eval (document. getelementbyid ('interactiveemitcode'). Value)" type = "button"> RUN </button>
<Button onclick = "Stop ();" type = "button"> stop </button>
<Canvas id = "interactiveemitcanvas" width = "400" Height = "400"> </canvas>
Summary
This article introduces the simplest kinematics simulation, uses Euler's method for numerical integration, and uses this method to implement a particle system with a simple collision. The essence of this article is actually only two simple formulas (only two adders and two multiplier). I hope readers can understand that physical simulation can be very simple. Although the example in this article is in a two-dimensional space, but this example can be extended to a three-dimensional space, you only need to replace vector2 with vector3. CompleteSource codeDownloadable.
We will continue the talks and add other physical phenomena on this basis, and have the opportunity to join other physical simulation topics. I hope you can support it and give me more comments.