# The front end that doesn’t understand physics is not a good game developer (I) — Fundamentals of physics engine

Time：2022-1-4

### summary

The game now seems to have become a way of entertainment that we can’t get around. From large-scale end games to mobile games, to page games, and then to H5 games in various apps, it has invaded our lives in various ways. So while enjoying the game, as a front-end developer, he also began to think about how to develop a game. What should it have at the technical level?

In addition to the basic game screen, dynamic effect development and rendering functions, there is another thing worth exploring, that is, the physics engine. A good physics engine ensures that the interactive experience in the game is similar to that in reality, providing people with a better experience.

There are many useful physical engines, most of which are out of the box, but some people may not understand what the basic and underlying logic of the physical engine looks like. Starting from this issue, we will introduce the basics of the physics engine in several parts to let you know more about it. The following contents refer to game physics engine development.

### What is an engine

What is the engine? Of course, this extends the concept of engine in automobile. In automobile, engine, an energy conversion device, converts other energy into mechanical energy and provides it to automobile. It is the core module of automobile movement.

What is the corresponding engine under development? In my understanding, it is a core module that can quickly add functions to the project and ensure the operation of functions. The rendering engine can quickly render the content. Game engine can quickly realize the basic development of a game. The physics engine can quickly simulate the physical state in reality.

After knowing what the engine is, we can pay more attention to the characteristics of the engine. The biggest features of the engine are two——fastcurrency。 It can quickly realize the required functions and has strong universality. It is not developed for a specific business, but for a large class of situations, so it must have strong universality.

Fast means complete functions, complete API packaging and convenient use. Universal means that the logic of the code itself needs enough bottom layer, and the application of the most basic logic can achieve the greatest universality.

### Fundamentals of physics engine

What is the basis of a physics engine? That is physics and mathematics. In fact, the embodiment of a physical system in the game is the position of each object in the whole physical system. Each frame needs to calculate the position of objects so that they can appear in the right place. Therefore, mathematical operation in accordance with the laws of physics is the basis of a physics engine. Everything below is based on this.

### Mathematics in code

First, let’s look at where mathematics plays a role in the game world. Whether in the two-dimensional or three-dimensional world, the description of the position of the object is completed by the vector. The processing of vector is inevitably some knowledge of vector itself, such as decomposition, addition and subtraction, point product, vector product and so on.

Therefore, we must first establish a most basic vector class:

class Vector {
x: number
y: number
z: number
constructor(x: number,y: number,z: number) {
this.x = x
this.y = y
this.z = z
}

setX(x: number) {
this.x = x
}

setY(y: number) {
this.y = y
}

setZ(z: number) {
this.z = z
}
}

The decomposition of vector applies the content of trigonometric function. A vector is decomposed into x-axis, Y-axis and z-axis through angle, or the corresponding angle is calculated according to the coordinates on different axes.

trigonometric function

The calculation principle of vector is not elaborated in detail. In the game world, it will be decomposed to the direction of the corresponding coordinate axis for calculation, even point product or vector product is no exception. Therefore, as long as you skillfully use trigonometric functions and vector calculation formulas, you can deal with vectors.

We will add the following calculation method to the vector:

class VectorOperation {
return new Vector(
vectorA.x + vectorB.x,
vectorA.y + vectorB.y,
vectorA.z + vectorB.z
)
}

Minus (vectora: vector, vectorb: vector) {// vector subtraction
return new Vector(
vectorA.x - vectorB.x,
vectorA.y - vectorB.y,
vectorA.z - vectorB.z
)
}

Multiply (vector A: vector, times: number) {// vector scaling
return new Vector(
vectorA.x * times,
vectorA.y * times,
vectorA.z * times
)
}

Dotproduct (vectora: vector, vectorb: vector) {// vector dot product
return vectorA.x* vectorB.x + vectorA.y* vectorB.y + vectorA.z* vectorB.z
}

Vectorproduct (vectora: vector, vectorb: vector) {// vector outer product
return new Vector(
vectorA.y * vectorB.z - vectorA.z * vectorB.y,
vectorA.z * vectorB.x - vectorA.x * vectorB.z,
vectorA.x * vectorB.y - vectorA.y * vectorB.x,
)
}
}

In game physics, we also need to use a very important mathematical knowledge, that is calculus.

So you may not realize that they are all basic physical contents. Why do you use differentiation and integration? For example, let’s take a look at the most basic speed formula. Starting from the average speed, it is the distance divided by the time:
$$v = \frac {s_{1} – s_ {0}}{t_{1} – t_ {0}} \ tag {average speed}$$

Then the calculation of the speed at a certain time is actually to reduce the time difference to infinity on the basis of the average speed:
$$v = \lim_ {\ delta T \ to 0} \ frac {\ Delta s} {\ delta T} = \ frac {DS} {DT} \ tag {speed}$$

Principle of differential

This is the application of differentiation. What about the application of integral?

Let’s look at the most basic formula of speed and distance. The formula in uniform motion is as follows, where t is the motion time:
$$s_ {1} = s_ {0} + v_ {0} t \ tag {uniform motion}$$

In fact, the essence of this formula should be:
$$s_ {1} = s_ {0} + \int_ {t_{0}}^{t_{1}}v_ {0}dt \ tag {uniform motion}$$

The above is just a simple application of calculus, which shows that the use of calculus in the game is also very important, so we should also add corresponding methods to the code.

### physical base

In a virtual world, if we want to get the same experience as reality, we must follow the physical laws in reality. It is impossible for apples to fly upward. Therefore, we first build an object that simulates the real environment.

What attributes should an object have in a physics engine? The most important is the position information mentioned above, so the corresponding information is the information of changing the position, that is, the speed. Then there is a value, that is, the information of changing speed, that is, acceleration. On this basis, we can get the attributes that the most basic object should have:

class GameObj {
pos: Vector
velocity: Vector
acceleration: Vector

constructor(pos?: Vector, velocity?: Vector, acceleration?: Vector) {
this.pos = pos || new Vector(0, 0, 0)
this.velocity = velocity || new Vector(0, 0, 0)
this.acceleration = acceleration || new Vector(0, 0, 0)
}

setPos (pos: Vector) {
this.pos = pos
}

setVelocity (velocity: Vector) {
this.velocity = velocity
}

setAcceleration (acceleration: Vector) {
this.acceleration = acceleration
}
}

We now have the most basic object. If we want to integrate this object into the physical system and operate it arbitrarily, we need to combine the object with the force. The combination of the two is Newton’s three laws.

The first is Newton’s second law. Force can change the motion state of an object. A simple formula is:

$$\ VEC f = m \ VEC a \ tag {Newton’s second law}$$

That is to say, if we want to combine acceleration and force, we need to give the object a variable, that is, mass M. Then we add the quality attribute to the above object:

class GameObj {
MES: number // quality must not be 0

constructor(mess?: number) {
if (mess > 0) {
this.mess = mess
}
}

setMess (mess: number) {
if (mess > 0) {
this.mess = mess
}
}
}

But at this time, we will have two problems: first, the mass of the object cannot be 0. If 0 is set, it will lead to an error in the quality setting; Second, for some objects, we need them to have infinite mass, such as ground and wall. We need them to remain fixed in the game scene. On the one hand, 0 is not allowed, and on the other hand, infinity is difficult to set. What should we do?

In game physics, a concept called inverse mass is proposed, which skillfully solves this problem. The inverse mass is actually the reciprocal of the mass, that is $\ frac {1} {m}$. In this way, we only need to set the inverse mass of the object to be fixed to 0 to make its mass infinite, and avoid setting the mass to 0.

class GameObj {
Inversemess: number // quality must not be 0

constructor(inverseMess?: number) {
if (inverseMess >= 0) {
this.inverseMess = inverseMess
}
}

setInverseMess (inverseMess: number) {
if (inverseMess >= 0) {
this.inverseMess = inverseMess
}
}
}

### epilogue

So far, the most basic mathematical and physical knowledge we need has been successfully injected into the physics engine, but this is only the cornerstone of a physics engine. On this basis, we have to add a variety of things, such as gravity, resistance, momentum, angular momentum, collision and so on. There is still a long way to go, and I will show them one by one in this series.

Welcome to the lab blog:aotu.io

Or focus on the official account of bump Laboratory (AOTULabs).

## ❤ Ten minutes to quickly learn to use the full stack of nodejs to develop wechat official account [recommended collection]

Original address:https://blog.csdn.net/qq_32442973/article/details/120475806 1、 Prepare Registered wechat subscription number Registered applet test number Sunny ngrok tool installation and account registration Note: the prototype of sunny ngrok is ngrok, but ngrok is foreign. Sunny ngrok is a domestic private server, which is faster. Its main function is domain name forwarding, simulating public network IP and port, and […]