When developing video games, we often encounter the problem of calculating the angle of a shot to hit a target. It's so common that I literally
for every game I worked on.
When this problem arose, I usually took a pen and pad and solved it from scratch. I am tired of this. To save my future self some time, I'll post this solution online. In addition, I will talk about an unusual “trick” that I prefer to use for aesthetic reasons.
Equations of motion
The task always starts the same way.
We have a shooter and a target: at what angle must the projectile be fired in order for it to hit the target? There are four basic equations of motion. In this article we will use only one.
To explain it in words, the final position is EQUAL to the starting position PLUS the velocity times the time PLUS half the acceleration times the time squared. This is a simple equation that requires a little algebra and a few trigonometric identities to solve.
Range
When developing video games, we will likely need to know the maximum range of a projectile.
The AI needs to understand how close to get, and players need clear, visual indicators of danger zones. There is a very simple equation for maximum range on a flat surface. We will immediately rush into the pool headlong and start with a generalized view.
If a projectile with constant speed (S) and gravity (G) is given, what will be its maximum flight range?
- Let us substitute the variables known to us (y0, S, G) into the basic equation of motion.
- Let's apply the formula for the roots of a quadratic equation. Let's discard the smaller value.
- Let's substitute t into x = S*cos θ*t and simplify.
Explosion.
Experiments in the field of explosion are carried out both with chemical explosives in quantities measured in grams and with nuclear charges with a yield of up to several megatons. Explosions can occur in a variety of environments, such as earth and rock, underwater, near the surface of the earth in normal atmospheric conditions, or in thin air at high altitudes. The main result of the explosion is the formation of a shock wave in the environment. The shock wave propagates from the explosion site at first at a speed exceeding the speed of sound in the medium; then, as the intensity of the shock wave decreases, its speed approaches the speed of sound. Shock waves (in the air, water, ground) can hit enemy personnel, destroy underground fortifications, sea vessels, buildings, ground vehicles, aircraft, missiles and satellites.
To simulate intense shock waves that occur in the atmosphere and near the surface of the earth during nuclear explosions, special devices called shock tubes are used. The shock tube is typically a long tube made up of two sections. At one end there is a compression chamber, which is filled with air or other gas compressed to a relatively high pressure. Its other end is an expansion chamber open to the atmosphere. When the thin diaphragm separating two sections of the pipe instantly ruptures, a shock wave appears in the expansion chamber, traveling along its axis. In Fig. Figure 4 shows shock wave pressure curves in three cross sections of the pipe. In section 3 it takes the classical form of a shock wave arising during detonation. Miniature models can be placed inside the shock tubes, which will undergo shock loads similar to the effects of a nuclear explosion. Tests are often carried out in which larger models and sometimes full-scale objects are exposed to explosions.
Experimental studies are complemented by theoretical ones, and semi-empirical rules are developed that make it possible to predict the destructive effect of an explosion. The results of such research are used in the design of warheads for intercontinental ballistic missiles and anti-missile systems. Data of this kind are also necessary when designing missile silos and underground shelters to protect the population from the explosive effects of nuclear weapons.
To solve specific problems characteristic of the upper layers of the atmosphere, there are special chambers in which high-altitude conditions are simulated. One of these tasks is assessing the reduction in explosion force at high altitudes.
Research is also being conducted to measure the intensity and duration of the shock wave in the ground that occurs during underground explosions. The propagation of such shock waves is influenced by the type of soil and the degree of its layering. Laboratory experiments are carried out with chemical explosives in quantities of less than 0.5 kg, while in full-scale experiments the charges can be measured in hundreds of tons. Such experiments are complemented by theoretical studies. The research results are used not only to improve the design of weapons and shelters, but also to detect unauthorized underground nuclear explosions. Detonation research requires fundamental research in solid state physics, chemical physics, gas dynamics and metal physics.
Firing angle to hit a stationary target
Now things get interesting.
If a projectile has a constant speed (S) and gravity is (G), then at what angle must it be fired to hit a stationary target?
Bach. Now we have two equations and two unknowns. Let's analyze them.
- First equation, two unknowns (t, θ)
- Second equation, two unknowns (t, θ)
- Calculate t from (1)
- Substitute (3) into (2)
- Trigonometric substitution: sin θ/cosθ = tanθ
- Trigonometric substitution: 1/(cos θ)^2 = 1 + (tan θ)^2
- Let's expand and transform
- Formula for the roots of a quadratic equation
- Multiply the top/bottom by -S^2/x. Let's move S^4/x^2 to the root
- Apply arctangent to each part
TA-dah! As a result, we got two angles. One high and one low. Here's what it looks like in practice.
BALLISTICS AT THE END POINT
Endpoint ballistics examines the physics of the destructive effect of weapons on the targets they hit. Its data is used to improve most weapons systems - from rifles and hand grenades to nuclear warheads delivered to the target by intercontinental ballistic missiles, as well as protective equipment - soldiers' body armor, tank armor, underground shelters, etc. Both experimental and theoretical studies are conducted on the phenomena of explosion (chemical explosives or nuclear charges), detonation, penetration of bullets and fragments into various environments, shock waves in water and soil, combustion and nuclear radiation.
Visual imperfection
Take a look at the gif shown above.
Once the kettle starts firing, things look pretty good. The high arc is beautiful and pleasing to the eye. The low arc feels crisp and effective. However, as the range increases, everything becomes less beautiful. The low arc is almost flat. The high arc is excessively high. This is the problem with a constant velocity projectile. It only looks good when the target is on the edge of its range.
Is there a better way?
Combustion.
Research in the field of ignition and combustion is carried out for a twofold purpose. The first is to obtain the data necessary to increase the ability of bullets, shrapnel and incendiary shells to cause fires in the fuel systems of aircraft, missiles, tanks, etc. The second is to increase the protection of vehicles and stationary objects from the incendiary effects of enemy ammunition. Research is being conducted to determine the flammability of various fuels under the influence of various means of ignition - electrical sparks, pyrophoric (self-igniting) materials, high-velocity fragments and chemical igniters.
Horizontal speed
I often prefer to set the projectile's horizontal velocity, just in the ground plane. Then I can explicitly set the height of the arc. That is, speed and gravity
.
This approach has many advantages. First of all, he always looks beautiful!
Secondly, its design is more intuitive. Designers don't care about absolute speed. They care that the turret has a range of 20 meters and that it takes 1 second for the projectiles to travel that distance. They are not required to use a charting calculator to change balance values. And artistic changes should not affect gameplay mechanics.
Thirdly, it’s easier to hit a moving target. I'll expand on this a little later.
This is what it looks like:
Barrel acceleration systems.
Also on topic:
ARTILLERY
The general classical problem of internal ballistics, as applied to barreled systems of initial acceleration of a projectile, is to find the limiting relationships between the loading characteristics and the ballistic elements of the shot, which together completely determine the firing process. Loading characteristics are the dimensions of the powder chamber and bore, the design and shape of the rifling, as well as the mass of the powder charge, projectile and gun. Ballistic elements are gas pressure, temperature of gunpowder and powder gases, speed of gases and projectile, distance traveled by the projectile, and the amount of gases currently active. The gun is essentially a single-stroke internal combustion engine in which the projectile moves like a free piston under the pressure of a rapidly expanding gas.
The pressure resulting from the transformation of a solid combustible substance (gunpowder) into gas rises very quickly to a maximum value of 70 to 500 MPa. As the projectile moves down the barrel, the pressure drops quite quickly. The duration of high pressure is on the order of several milliseconds for a rifle and several tenths of a second for large-caliber weapons (Fig. 1).
The characteristics of the internal ballistics of the barrel acceleration system depend on the chemical composition of the propellant, its burning rate, the shape and size of the powder charge, and the loading density (the mass of the powder charge per unit volume of the gun chamber). In addition, the characteristics of the system can be affected by the length of the gun barrel, the volume of the powder chamber, the mass and “lateral density” of the projectile (the mass of the projectile divided by the square of its diameter). From an internal ballistics point of view, low density is desirable because it allows the projectile to achieve greater velocity.
To keep a recoil gun in balance during a shot, a significant external force is required (Fig. 2). External force is typically provided by a recoil mechanism consisting of mechanical springs, hydraulic devices and gas shock absorbers designed to dampen the rearward impulse of the gun's barrel and breech. (Momentum, or momentum, is defined as the product of mass and velocity; by Newton's third law, the momentum imparted to the gun is equal to the momentum imparted to the projectile.)
In a recoilless rifle, no external force is required to maintain the equilibrium of the system, since here the total change in impulse imparted to all elements of the system (gases, projectile, barrel and breech) for a given time is zero. To prevent a weapon from recoil, the momentum of the gases and projectile moving forward must be equal and opposite to the momentum of the gases moving backward and exiting through the breech.
Calculation of horizontal movement speed
If a projectile with horizontal velocity (S) and peak height (y_peak) is given, what must the velocity and gravity be to hit a stationary target?
- Basic equation of motion
- Solve (1) by substituting 2
- Let's set what y_peak (user constant) the projectile reaches at time (1/2)t
- Let us set what y_end (target height) the projectile reaches at time t
- Magic!
- More magic!
- The shooting vector is equal to (S, vy) with gravitational acceleration g
Voila!
Wait a minute though. Magic? This is a scam! Yes, but quite justified. Points (3) and (4) are two more equations with two unknowns. I'm lazy and don't want to write them down. Plus I'll get confused and mix up the sign, so I'll let the computer solve them for me.
More precisely, I used Wolfram Alpha. I recommend everyone to have Wolfram in their toolkit, it is quite useful.
If a+c == 2b, then y0, y_peak and y_end lie on the same straight line. That is, we shoot in a straight line.
Speed of horizontal movement with a moving target
So we have two different trajectory calculations. However, enemies usually do not stand still, they move. We need to calculate the trajectory to hit moving
target.
This is where all the advantages of horizontal movement speed come into play. By specifying ground velocity, it is very easy to perform calculations for a moving target.
- Where X is the position of the target, and V is its speed
- We square both parts.
- Convert to a quadratic equation
- We apply the formula for the roots of a quadratic equation
See points 5 to 9 in the previous section. This makes me very happy. Pew-pew-pew!
Constant speed with moving target
But what if we need to hit a moving target with a projectile at a constant speed?
Oh-oh. This is a very confusing task! I don’t even know how to approach her. In my entire career I have never had to solve it. Games usually don't require precision artillery. It's just not interesting! Instead, we approximate the future position and aim at a random point near it. Players perceive artillery fire as a shower of stupid shells rather than laser-guided guaranteed death.
In the process of writing this post, I found a solution to the problem of a projectile with a constant speed and a moving target, which was not available on the Internet in finished form. It's worth noting that you probably won't need to implement it in your game. But I spent a lot of time on it, so I don't want it to go to waste!
Fourth degree equations
Most likely, you won't want to use it in your game precisely because of the fourth degree equations. Essentially, the solution requires one of these equations.
Quadratic equations have a simple and elegant solution in the form of the formula for the roots of a quadratic equation.
Cubic equations can be solved in several different ways. However, equations of the fourth degree are a real headache. Solving such equations is far beyond the scope of this article. Honestly, and beyond my mathematical abilities. Luckily for us, the 1990 book Graphics Gems I has code for solving fourth-order equations. I used this code for my demo. I cannot guarantee its accuracy or numerical stability; use it with extreme caution.
Method one
So let's solve it. What should be the angle at which a projectile is fired at a constant speed at a moving target? This method is taken from a 2007 post by James McNeill and updated with information from Ryan Jackett.
- Where P is the target position and V is the target speed
- Square both sides
- Let's transform
- We calculate the coefficients of the fourth order equation and insert it into SolveQuartic
- We use t to calculate the position of the target when calculating the trajectory to a fixed point.
The method works. All complex tasks are performed by SolveQuartic. We then use the stationary target solution outlined above.
Method two
Before I found the first way, I came up with a solution in another way. It consists of many more steps. However, I find the end result more elegant. Plus I wasted about eight sheets of paper and I don't want those trees to sacrifice themselves for nothing.
Damn it. 32 steps!? It's worse than it seems.
1–7
— declare variables.
8–11
— we declare a system of equations. Four equations, four unknowns - d, e, f, t.
12–15
— we calculate the value of d using (8). Multiply d^2 by the future.
16–19
— we calculate the value of f using (10). Multiply f^2 by the future.
20–24
— we calculate the value of e using (9). Multiply e^2 by the future.
25–27
— we calculate the value of e^2 using (11). Substitute d^2 and f^2.
28–30
— we equate (27) to (24). We multiply by t^2 and transform it into a fourth-degree equation.
31
— we substitute the coefficients in SolveQuartic.
32
— substitute positive real roots into (14), (18), (23) for d, e, f.
The code is quite short. There are more lines devoted to variable declarations than to the calculations themselves! Of course, except for SolveQuartic.
Fragments and penetration ability.
Fragmentation warheads and projectiles have a metal outer shell, which, upon detonation of the chemical high explosive charge enclosed in it, breaks into numerous pieces (fragments) that fly apart at high speed. During World War II, projectiles and warheads with shaped charges were developed. Such a charge is usually a cylinder of explosive, at the front end of which there is a conical recess with a conical metal liner, usually copper, placed in it. When an explosion begins at the other end of the explosive charge and the liner is compressed under the influence of very high detonation pressures, a thin cumulative jet of liner material is formed, flying towards the target at a speed of more than 7 km/s. Such a jet is capable of penetrating steel armor tens of centimeters thick. The process of formation of a jet in ammunition with a charge of cumulative action is shown in Fig. 5.
If the metal is in direct contact with the explosive, shock wave pressures measured in tens of thousands of MPa can be transferred to it. With a typical explosive charge size of about 10 cm, the duration of the pressure pulse is a fraction of a millisecond. Such enormous pressures acting for a short time cause unusual destruction processes. An example of such phenomena is “chipping”. The detonation of a thin layer of explosives placed on an armor plate creates a very strong short-duration pressure pulse (impact) running through the thickness of the plate. Having reached the opposite side of the slab, the shock wave is reflected as a wave of tensile stresses. If the intensity of the stress wave exceeds the tensile strength of the armor material, tensile failure occurs near the surface at a depth depending on the initial thickness of the explosive charge and the speed of propagation of the shock wave in the plate. As a result of an internal rupture of the armor plate, a metal “shard” is formed, flying off the surface at high speed. Such a flying fragment can cause great destruction.
To clarify the mechanism of fracture phenomena, additional experiments are carried out in the field of metal physics of high-speed deformation. Such experiments are carried out both with polycrystalline metal materials and with single crystals of various metals. They made it possible to draw an interesting conclusion regarding the initiation of cracks and the beginning of destruction: in cases where there are inclusions (impurities) in the metal, cracks always begin at the inclusions. Experimental studies are being carried out on the penetrating ability of shells, fragments and bullets in different environments. Impact velocities range from several hundred meters per second for low-velocity bullets to cosmic velocities on the order of 3–30 km/s, consistent with fragments and micrometeors encountered by interplanetary vehicles.
Based on such studies, empirical formulas regarding penetrating power are derived. Thus, it has been established that the depth of penetration into a dense medium is directly proportional to the amount of movement of the projectile and inversely proportional to its cross-sectional area. The phenomena observed during an impact at hypersonic speed are shown in Fig. 6. Here a steel pellet hits a lead plate at a speed of 3000 m/s. At different times, measured in microseconds from the start of the collision, a sequence of X-ray images was taken. A crater forms on the surface of the plate, and as the images show, plate material is ejected from it. The results of the study of impacts at hypersonic speed make it more clear the formation of craters on celestial bodies, for example on the Moon, in places where meteorites fall.
Tools
I used several tools when creating this post. Many of them were new to me.
- Unity to create a demo.
- Paper, Affinity Designer and MSPaint for creating images.
- Arachnid Latex + MathJax for LaTeX formulas.
- FFmpeg for converting a sequence of screenshots into animation.
- Gfycat for embedding animations.
- Teapot from Utah. Pew Pew!
LaTeX syntax is terrible and difficult to learn. All LaTeX formulas can be found here. Here's an example: