[Huawei] [cloud technology sharing large monopolized the front end (8)] matter.js classical physics

Abstract introduced the use of front-end and basic physics engine matterjs combat

Sample code is hosted: http://www.github.com/dashnowords/blogs

1583842067707437.gif

1583842068298307.gif Front-end development in the field of physics engine is a relatively small minority of the topic, it is usually as an adjunct tool for game development engine of the emergence of independent functional demo works often gives the feeling of fun but nowhere available. The simulation is to simulate objects behave in the real world in the virtual world of the computer (dynamic simulation of the most common). Simulation allows the screen objects athletic performance more in line with the players perception of the real world, such as "Angry Birds" game is emitted slingshot birds or because they were hit and collapsed heap of objects, as well as in " cut the rope "game cut the rope after what happened pendulum or objects fall sports, and real-world performance are nearly the same, the game experience will usually be better.

With the physics engine can help developers to more quickly achieve such collision bounce, friction, pendulum, springs, fabric and so on different types of simulation results. Engines typically require physical handling and screen rendering is not related to the transaction, but only to complete the simulation calculation section on it, you can understand it as a model MVC layer M, a screen for rendering it theoretically layer V It is independent. matter.js based canvas2D API provides rendering engine, p2.js provides a renderer based on WebGL implemented in the example code, you can also find examples p2.js used in conjunction with CreateJS or Egret in the development community. Joint use game engine and physics engine did not imagine so complicated, in fact only need to complete the mapping coordinates between the different engines on it, skillfully developers may prefer the flexibility of this "low coupling" will bring , but for junior developers, undoubtedly increase the threshold for the use.

I. Review of classical mechanics

The basic laws of classical mechanics is Newton's three laws of motion or related to mechanics, it can be used to describe the movement of objects in the macroscopic world low speeds, but also provides the basis for the calculation of physics simulation game development, most simulations are are calculated based on the formula of classical mechanics simulation, or a simplified form, the usage is high Law equation comprising:

  • Newton's first law

    Newton's first law, also known as the law of inertia, it pointed out that any object must maintain a uniform linear motion or rest, until the external force it to change the state of motion so far.

  • Newton's second law

    Newton's second law is inversely proportional to the external force refers to the mass and the acceleration of an object it suffered, and the object, the object direction acceleration force suffered the same engagement speed, which can simulate the process of acceleration and deceleration of the object, is calculated as ( F is a resultant force, m is mass of the object, a is acceleration):

1583842113607916.png

  • Momentum conservation theorem

    If a system is not an external force or external force vector is zero, then the total momentum of the system remains unchanged, i.e., the momentum of mass m and velocity v of the product, it is often used to simulate two objects collide, the law of conservation of momentum the formula can be derived from Newton's second law deriving (F is a resultant force, duration of action t, m is the mass of the object, v2 is the terminal velocity, v1 is the initial velocity):

1583842136788623.png

  • Theorem of kinetic energy of bonding work done external object, the kinetic energy of an object is equal to the amount of change, the formula is expressed as follows (W is acting resultant force, m is mass of the object, v2 is the terminal velocity, v1 is the initial velocity):

1583842157227420.png

     When the resultant force is a constant force, that the work done can be calculated by the following formula (W is acting resultant force, F is the resultant force size, S is the movement distance of the object):

1583842228192926.png

 

  • Hooke's Law

    Hooke's law states that when the spring is elastically deformed, the elastic force F of the spring and its elongation (or compression) is proportional to x, which is the main basis for the physical simulator elastic correlation calculation, the correlation formula is as follows (represented by spring force F, k represents a spring constant, x denotes the difference in length and the length of the spring when no stretch):

    spacer.gif1583842241543876.png

Use the relevant principles classical mechanics, the physical properties of the object can be simulated in a computer, for analog uniform circular motion, pendulum, electromagnetic fields, etc. can be simulated based on physical principles related to, this section will not start.

II. The principle of simulation

2.1 The basic dynamics simulation

Canvas is a process of animation frame by frame rendering, physics engine principle is to increase the role of the physical attributes of abstract entities, their values ​​updated in each frame and to calculate the impact of these physical cause, and then execute the command drawn. When objects need to mass dynamics simulation, combined force, velocity, acceleration and other attributes, wherein the quality is a scalar value (i.e. not direction value), the combined force, velocity and acceleration are vector values ​​(directional value). Whether in 2D or 3D graphics calculations, the vector calculation frequency is very high, if not packaged, the code might flooded with underlying mathematical code that affect the readability of the code, in order to facilitate the calculation, we first common actions encapsulate the two-dimensional vector:

/*二维向量类定义*/class Vector2{    constructor(x, y){        this.x = x;        this.y = y;    }    copy() {        return new Vector2(this.x, this.y);     }    length() {         return Math.sqrt(this.x * this.x + this.y * this.y);    }    sqrLength() {         return this.x * this.x + this.y * this.y;     }    normalize:() {         var inv = 1 / this.length();         return new Vector2(this.x * inv, this.y * inv);    }    negate() {         return new Vector2(-this.x, -this.y);     }    add(v) {         return new Vector2(this.x + v.x, this.y + v.y);     }    subtract(v) {         return new Vector2(this.x - v.x, this.y - v.y);     }    multiply(f) {         return new Vector2(this.x * f, this.y * f);     }    divide(f) {         var invf = 1 / f;         return new Vector2(this.x * invf, this.y * invf);    }    dot(v) {         return this.x * v.x + this.y * v.y;     }}

To make the simulation object instance has the necessary attributes structure, you can define an abstract class, then the class of objects to inherit it can, and this time you usually write React application with custom classes inherit React.Component is the same, example pseudo-code as follows:

class AbstractSprite{    constructor(){            this.mass = 1; //物体质量            this.velocity = new Vector2(0, 0);//速度            this.force = new Vector2(0, 0);//合外力            this.position = new Vector2(0, 0);//物体的初始位置            this.rotate = 0; //物体相对于自己对称中心的旋转角度    }}

We did not add acceleration in properties, and the use of combined force can calculate its mass, position attribute is used to determine the position of the object drawn, Rotate attribute is used to determine the deflection angle of the object, the properties listed above in the calculation of common linear motion the scene is enough. Indeed choice property and there is no uniform standard, such as to simulate the movement of celestial bodies, may also need to add the rotation angular velocity, the revolution angular speed, if you want to simulate the spring, it may be necessary to add elastic modulus, equilibrium length, if you want to simulate pool rolling performance, you need to add friction, the selected property is usually directly or indirectly affect the final object visible shape on the canvas, you can declare these specific scenarios will be used to attribute in the subclass. Declare a new object class sample code is as follows:

class AirPlane extends AbstractSprite{    constructor(props){        super(props);        /* 声明一些子属性 */        this.someProp = props.someProps;    }    /* 定义如何更新参数 */    update(){}    /* 定义如何绘制 */    paint(){}}

The above template code believe that you are already familiar with, and to update the code written in the state attribute update function can, in theory, the update function execution interval is about 16.7ms, the calculation process can be approximated that property is unchanged. We know that the acceleration in the accumulation time dimension affects the speed, the speed of accumulation over time the impact of displacement:

Simulation process [Delta] t is the custom, you can go to adjust it in accordance with the desired visual effect, the greater the [Delta] t, the same size of the observed effect of the physical quantity in each frame caused more significant when using the vector update computation is performed :

this.velocity = this.velocity.add(this.force.divide(this.mass).multiply(t));this.position = this.position.add(this.velocity.multiply(t));

Movement Simulation need to pay more attention to the smaller volume of the object, but faster, because it is based on bounding box may fail to detect, for example, associated with particle simulation scenario, based on gravity and particle motion, than the initial distance far closer to each other during the particle velocity is faster, which may make the two successive calculations, the two particles are not overlapping bounding boxes, but in fact they have had a collision, and computer simulations will be because of the animation frame by frame discrete miss collisions screen, then the two particles will start doing deceleration movement away from each other, the overall state of motion will be presented as simple harmonic motion form. Therefore, when a collision detection system for a particle, in addition to the bounding box, and generally also the association rate and direction of change of acceleration values ​​to perform comprehensive determination.

2.2 crash simulation

Collision, refers to two or two objects in motion near or into contact with each other, strong interaction occurs during a short time, it usually will cause a change in the state of motion of the object. Crash simulation is generally used to calculate completely elastic collision, it is an ideal condition of energy loss does not occur during the collision is assumed, such a collision process can use the law of conservation of momentum and kinetic energy conservation law is calculated:

1583842272360248.png

Only formula V1 'and V2' are unknown, simultaneous equations is calculated on the rear-end collision speed can be obtained:

1583842284222229.png

 

When the engine detects a collision occurs just after the collision velocity is calculated according to the equation it can be seen in the formula used to attribute has been declared in the abstract object class should be noted that the speed of synthesis is required vector operations. Perfectly elastic collision for convenience only scenario calculations, in most cases we do not need to know the exact value of the collision energy losses, so if you want to simulate the energy loss caused by the collision, you can always after each collision system kinetic energy multiplied by a coefficient between 0 and 1 for the purpose.

1583842298271187.png

 

Another typical scenario occurs between the non-central collision object, i.e. the extension line direction of movement of the object does not pass through the centroid another object to simplify the calculation when the motion simulation usually ignored due to collisions caused by the rotation of the object, the speed of the object to be decomposed into another direction toward the center of mass of the component and the material component perpendicular to the connection, then the formula for the elastic collision of the heart to solve part of the central collisions, before and then after the final speed collision the vertical component of the speed obtained after the synthesis of a collision.

You do not have to worry about the physical simulation tedious calculations details, most commonly used scenes can be used to achieve rapid physics engine, not to repeat learning principles to create some simple "wheel", but to let you do not apply in the face of the engine you can go to achieve the appropriate development time scene.

III. Physics engine matter.js

3.1 "angry bird" physical characteristics analysis

"Angry Birds" is a very rich physical elements of the game, this section as an example be a simple exercise. Game first need to achieve a simulation of ground otherwise, all objects will fall directly to the outside of the canvas, and then need to make a slingshot, when the player presses the mouse and drag to the left on the slingshot, slingshot rubber band will be stretched, and the middle of a bird about to be ejected will appear. When the player releases the mouse slingshot rubber band stretched since the accumulated elastic energy is gradually transformed into the kinetic energy of the birds, so that the bird is emitted, when the initial speed of the bird is obliquely upward, in the subsequent motion process will be affected because of gravity and air resistance is gradually changed, and the same size vertically downward gravity, and aerodynamic drag direction opposite closing speed, throughout the flight speed of the need to update the birds in each frame. Right of the screen is usually static objects a stack of objects by a variety of different materials and green sets consisting of pig, bird striking an object when the stack, the stack will collapse the object, the object stack the various components will follow revision of the laws of physics constraints state, thus showing the effect of the simulation, the object stack pressure to collapse which would destroy the green pig, the pig when all have been eliminated, can enter the next level.

1583842367797185.jpg

Let's use matter.js physical model for the whole scene, and then use CreateJS rendering model established by coordinates and angle synchronization to add static or dynamic map for each physical model. In order to reduce the difficulty of modeling, in the exemplary simplified model of the rubber band slingshot in this section is a spring, as long as the bird can be ejected.

3.2 Construction of a physical model using matter.js

The sample code matter.js official website provides the following, it can help developers familiar with the basic concepts and development process, you can [official] positions the code to find more sample code:

var Engine = Matter.Engine,      Render = Matter.Render,    World = Matter.World,     Bodies = Matter.Bodies; // create an engine var engine = Engine.create(); // create a renderer var render = Render.create({    element: document.body,    engine: engine}); // create two boxes and a ground var boxA = Bodies.rectangle(400, 200, 80, 80); var boxB = Bodies.rectangle(450, 50, 80, 80); var ground = Bodies.rectangle(400, 610, 810, 60, { isStatic: true }); // add all of the bodies to the world World.add(engine.world, [boxA, boxB, ground]); // run the engine Engine.run(engine); // run the renderer Render.run(render);

In the sample code to include primarily responsible for the physical concept of calculating Engine (engine), is responsible for rendering the screen Render (renderer), which manages object World (the world) and a rigid Bodies drawing (object), course, this is the basic function of matter.js. Matter.Render speed by varying the parameters passed, can mark the object in the picture, acceleration, direction, and other debug information, the object may be directly rendered wireframe model, it is very simple in a debugging environment or some scenarios easy to use, but when faced with more complex needs such as sprite animation management, you need to be manually extended or a direct replacement for the renderer.

In physical modeling "angry bird" process, static property is set to true by default rigid body has infinite quality, does not participate in this type of rigid body collision calculation, only the objects they encounter bounce back, if you do not want allow objects to the world of flying boundary of the canvas, just add a static rigid bodies were in four sides of the canvas on it. Establishment is also very easy to stack object, a commonly used rectangular, circular, polygonal profile can be used directly to create the object Bodies, position coordinates of the reference point is the center of the default object. When the object has an initial position in the world in the area of ​​overlap occurs, the engine will be based on direct collision to handle at work, which might lead to some unexpected object has initial velocity, in the debugging process by activating the body model the isStatic property to be declared as a static rigid, static rigid body will remain in his position and not because of collision detection relations exercise, so that you can detect the initial state of the model, as shown below:

1583842449345260.png

Construction spring model technique is referred to as "constrained", associated methods stored in the constrained module Matter.Constraint. Constraints exist separately and there is no practical significance, it takes two linked objects, is used to represent relationships between objects bound association, if only one object is associated, said constraints between the object and the coordinates of the fixing anchor , the default is fixed coordinate (0,0), by adjusting the position of the fixed attributes pointB pointA or anchor, spring model "angry bird" is used in the form of a single-fixed end. We just need to find the position of a transverse section through the slingshot is ejected when the birds, comprising establishing a coordinate value of the object as an anchor point, and then create a pattern of attachment points when a bird B rigid body dynamic pulling spring is used as a mouse, which finally create constraints between two objects on it, you declare when you create a constraint elastic stiffness coefficient, which indicates the degree of difficulty of the deformed constraints. Constraint in this example is coincident equilibrium positions of both ends together, when the player using the mouse to drag bird pattern attachment point away from equilibrium position, a spring can be seen rendering constraint between points on the screen, when the user Song after opening the mouse, the spring contracts, the attachment point will return to the initial position, the rebound process is a process similar to damp vibration, the larger the elastic coefficient constraints, the endpoint rebound smaller fluctuations in the equilibrium position. When the need to simulate the spring is compressed, it is necessary to define a balance by the distance constraint length property, this equilibrium will be restored to the restoration distance constraint. Sample code is as follows:

birdOptions = { mass: 10 },

bird = Matter.Bodies.circle(200, 340, 16, birdOptions),

anchor = { x: 200, y: 340 },

elastic = Matter.Constraint.create({

            pointA: anchor,

            bodyB: bird,

            length: 0.01, 

            stiffness: 0.25

        });

 Mouse and mouse module Matter.Mouse Matter.MouseConstraint restraint module provides the ability to track mouse events associated with the user interaction, with the Matter.Events module can move the mouse, click, drag and drop objects and other typical events to monitor, use relatively fixed, you only need to look at official documents, familiarize yourself with the engine supported event can be, the relevant sample code as follows:

//创建鼠标对象

var mouse = Mouse.create(render.canvas);

//创建鼠标约束

Var mouseConstraint = MouseConstraint.create(engine, {

            mouse: mouse,

            constraint: {

                stiffness: 0.2,

                render: {

                    visible: false

                }

            }

        });

 //监听全局鼠标拖拽事件

Events.on(mouseConstraint, 'startdrag', function(event){

    console.log(event);

})

Updated physics engine is also a frame by frame basis, you can use Matter.Events module to monitor engine events sent to afterUpdate update issued after each event is calculated, for example, in the callback function to determine whether the birds need to be ejected. Ejection player using the mouse to drag the bottom left and the mouse is released occurs, we can be determined based on the position of the ejection point of attachment of the bird, the bird when the anchor is in the upper right side and over a certain distance, which is determined to be emitted, the emitted logic is to generate a new point of attachment of the bird, the original constraint bodyB replacement, the original point of attachment performance constraints after releasing parabolic motion with a certain initial velocity, flying objects stack. Sample code is as follows:

const ejectDistance = 4; //定义弹射判断的位移阈值

const anchorX = 200; //定义弹簧锚点的x坐标

const anchorY = 350; //定义弹簧锚点的y坐标

//每轮更新后判断是否需要更新约束

Events.on(engine, 'afterUpdate', function () {

     if (mouseConstraint.mouse.button === -1 

&& bird.position.x > (anchorX + ejectDistance) 

&& bird.position.y < (anchorY - ejectDistance)) {

              bird = Bodies.circle(anchorX, anchorY, 16, birdOptions);

              World.add(engine.world, bird);

              elastic.bodyB = bird;

        }

    });

Note that the rigid body model will be constructed matter.js geometric center of the object as a positioning reference point. Thus, a simple physical model is constructed well, wireframe following effects:

spacer.gif1583842556834541.png

While seemingly simple, but it has a lot of physical characteristics can be simulated, and after the next section we map as a model, it will looks more like a game, a physical model of the complete code can be found in my code repository get in to.

3.3 physics engine game engine in hand

Renderer module Matter.Render matter.js provide physical model is very suitable for debugging, but in the face of the game is not strong enough to make Shihai, such as native Render module only supports static picture when the model map, and the game is often extensive use sprite animation to increase the fun, then the game engine and physics engine to use together is a very good choice.

When you Matter.Render related code are deleted, the page is no longer drawn pattern, but if you export some of the information in the console, you will find examples of listening afterUpdate event listener function still continues to perform, This means that the physics engine continues to work, constantly refresh the physical properties of the numerical model, but the picture is not rendered to the canvas only. Rendering work, we would naturally give the rendering engine to process, when using CreateJS to develop the game, rendering engine used is Easel.js. First, Easel.js establish all models stored in the physical space engine.world.bodies array corresponding view model, the so-called view model, refers to the visual appearance of an object, such as a rectangle may represent wood, stone may also represent blocks, depending on what kind of map you use to represent it, the view model can be a sprite sheet, or from any bitmap graphics Easel.js definition graphics support, the establishment of which in turn added to the stage after stage in the instance. Thus each object actually has two corresponding models, the model relies on the physical space physics engine updates, it is responsible for providing the position coordinates and rotation angles corresponding to the object in each frame, and to ensure compliance with the laws of physics trends; rendering stage the appearance of the style object model holds, relying rendering engine to draw and update, when you only need to update object attributes in each frame to key information about the physical model (usually the position coordinates and rotation angle) can be synchronized to the rendering model a. The basic logic flow is as follows:

1583842578525334.png

 

According to the code before the extension of the above process is not difficult, after the completion of the game screen looks much more interesting:

1583842594902845.png

 

The complete code has been uploaded to the code repository. I believe you have found, in the final screen layout and object physics engine layout is the same, the nature of the physics engine is to provide the correct coordinates and angles for each rendering model, and to ensure that data on a frame-update process changes and interaction in line with the laws of physics. If the third party physics engine can not meet your needs, then hands it to achieve its own engine, I believe you already know how to begin.

Author: Huawei's cloud experts enjoy  great history does not speak

Released 1070 original articles · won praise 5456 · Views 1.08 million +

Guess you like

Origin blog.csdn.net/devcloud/article/details/104813585