This article gives a brief illustration of Newton’s laws of motion in the plane and analyzes the tools that the Unity 2D engine makes available to programmers to simulate the movement of bodies in the 2D environment.

For the study of physics it’s essential to know the units of measurement of fundamental and derived quantities, as defined in the International System (SI). The basic quantities of mechanics are shown in the following table:

For an exhaustive review of the units of measurement, see this link to Wikipedia.

## 1) Concepts of kinematics

Kinematics is the branch of mechanics that studies the motion of bodies without considering the action of the forces involved. The main physical quantities under study are: position, speed and acceleration. The simplest case to study is that of a point-like body with negligible dimensions for the context in which it moves. We will use the standard term of **material point:** practically a geometric point, to which a mass \(m \) can be associated, that moves in the plane according to a certain trajectory.

### 1.1) Position

To specify the position of an object, a reference system must be chosen. For motion in a straight line a parameter is sufficient to specify the position of an object. In the plane we need two parameters, for example the coordinates \(x, y\) of a system of Cartesian axes. In the space we need three parameters. It’s useful to introduce the use of vectors; the position of an object located at a point \(P \) of the plane, with respect to the origin \(O \), can be defined by means of the position vector \(\mathbf{r}(t) \):

The **position vector** is a vector that begins at the origin of the reference system and ends at the point itself. In general, if the material point is moving, the position vector is a variable function over time. In the plane we can express the position vector as a function of the components with respect to the Cartesian axes:

### 1.2) Velocity

The velocity of a material point moving in the plane is defined as the variation of the position vector per unit time. It’s computed through the derivative with respect to time:

\[ \mathbf{v}(t) = \frac{d \mathbf{r}(t)}{dt} \]Therefore, velocity is a vector and can be decomposed into its components along the Cartesian axes:

\[ \mathbf{v}(t)= \frac{d x(t)}{dt} \mathbf{i}+\frac{d y(t)}{dt} \mathbf{j} \]### 1.3) Acceleration

The acceleration of an object is defined as the variation of the velocity vector per unit time. Velocity is a vector, therefore there may be acceleration because the modulus of velocity changes or because only the direction changes (as in uniform circular motion). The mathematical definition of acceleration is as follows:

\[ \mathbf{a}(t)=\frac{d \mathbf{v}(t)}{dt} = \frac{d^{2}x(t)}{dt^{2}} \mathbf{i}+ \frac{d^{2}y(t)}{dt^{2}} \mathbf{j} \]Knowing the expression of the vector position over time, we can calculate the speed and acceleration by means of derivative operations. Vice versa, knowing the expression of acceleration as a function of time, we can calculate the velocity and the position by means of integration operations:

\[ \begin{split} \mathbf{v}(t) &= \int_{t_{0}}^{t} \mathbf{a}(t) dt \\ \mathbf{r}(t) &= \int_{t_{0}}^{t} \mathbf{v}(t) dt \\ \end{split} \]**Example 1.1 – Uniformly accelerated motion**

Suppose that a body moves with constant acceleration \(\mathbf{a} \), and that at time \(t = 0 \) it has velocity equal to \(\mathbf {v}_{0} \) and it’s found in the position \(\mathbf {r}_{0} \). By applying the two integration operations described above we obtain the expression for velocity and position as a function of time:

These vector equations can be projected along the Cartesian axes, obtaining separate equations for the components of the velocity and of the position vector.

**Example 1.2**

An example of uniformly accelerated motion is that of a body that falls under the action of terrestrial gravity. Neglecting the air resistance, as we will see later, the body falls downwards with constant acceleration \(a = g \), where \(g = 9.8 ms^{- 2} \) is the acceleration of gravity, which we can consider constant near the surface of the Earth.

Another example of uniformly accelerated motion is a projectile launched from the origin of a Cartesian coordinate system, with an initial velocity vector \(\mathbf{v} = (v_{0, x}, v_ {0, y} ) \). Assuming that only the gravitational force of the earth is present and neglecting the resistance of the air, the projectile follows a parabolic trajectory. The above equations allow to calculate the point and time in which the projectile falls back to the ground.

## 2) Dynamics

Dynamics studies the motion of objects taking into account the mass and making a complete analysis of the forces involved. The dynamic analysis allows to predict the motion of the objects on which the forces act.

Typical examples are the motion of objects on the earth’s surface under the action of gravity, the motion of the planets around the sun, or the calculation of the time required to stop a car that moves at a given speed.

This article summarizes the main concepts and equations of motion dynamics. However, for an in-depth study we refer to physics texts, among which the following ones are excellent: ^{[1]} or ^{[2]}.

### 2.1) The forces

The concept of force is fundamental in physics. In the study of mechanics, we can define a force as an action that tends to maintain or modify the motion of an object. There are different types of forces. A useful distinction is that between contact forces and forces at a distance. The main forces acting at a distance are:

- gravitational force
- electric force
- magnetic force

Contact forces act between objects that physically touch each other. Contact forces include the following:

- friction (e.g. a body that rolls or crawls on a road)
- air resistance
- reaction force (e.g. an object on a table)
- collisions between two particles

The contact force model is a useful approximation in solving many problems. However, strictly speaking, given the atomic structure of matter, there is never a real physical contact between bodies and all forces should be treated as distance forces, even if the distances are microscopic.

A force is a vector quantity, which is measured in **Newton** in the International System. Once a reference system has been fixed in the plane, a force can be decomposed into its components according to the direction of the coordinated axes:

### 2.2) Newton’s three laws of dynamics

The concept of force was introduced by Isaac Newton in his fundamental work ‘**Philosophiae Naturalis Principia Mathematica**‘, published on July 5, 1687, which describes his famous three laws of dynamics.

Newton’s three laws of motion are as follows:

**law of inertia**: in an inertial reference system, every body not subject to forces remains in its state of rest or uniform rectilinear motion**law of force**: \(\mathbf{F} = m \mathbf{a} \)**principle of action-reaction**: to every action corresponds an equal and opposite reaction

The first law had already been formulated by **Galileo** and requires defining exactly the properties of inertial reference systems. For these concepts, that are not simple but very profound, we refer to the physics texts in the bibliography.

The second law expresses the fundamental discovery that forces are the cause of accelerated motions. If a force \(\mathbf{F} \) is exerted on a mass object \(m \), then the body experiences an acceleration of the value

The force is responsible for the acceleration of a material body. Constant velocity movement is possible without the action of forces, contrary to what ancient philosophers, such as Aristotle, believed.

The third law implies that if an object exerts a force on another object (for example a book placed on the table exerts a pressure on the table), then the second object exerts an equal and opposite reaction on the first object (the table exerts an equal and opposite force on the book).

### 2.3) Newton’s law of universal gravitation

An important example of application of Newton’s laws is the calculation of the trajectories of planets and satellites in the solar system. The universal law of gravitation discovered by Newton states that, given two bodies of masses \(m, M \) respectively which are at a distance \(r \), a gravitational force of attraction is exerted between them. The intensity of the gravitational force is expressed by the following Newton formula:

\[ \mathbf{F} = G \frac{mM}{r^{2}} \mathbf{u_{r}} \]where \(G = 6,67 \cdot 10^{- 11} m^{3} (Kg)^{- 1} s^{- 2} \) is the famous **universal gravitation constant**. The vector \(\mathbf{u_{r}} \) is a unit vector, with direction equal to the radius vector joining the two material points.

Due to the small value of the constant \(G \), the gravitational force is very weak if the masses involved are not large. For objects that are close to the surface of the Earth, Newton’s formula can be simplified in this way:

where \(g = 9.8 ms^{- 2} \) is the constant value of acceleration and the direction is perpendicular to the surface of the earth. In essence, near the surface of the Earth the force of gravity does not depend on the distance between the body and the Earth; all bodies, of any mass, have the same acceleration, neglecting the resistance of the air and other possible forces.

**Example 2.1 – Motion of a bullet**

A bullet is launched from the origin of a Cartesian coordinate system, with an initial velocity vector \(\mathbf {v} = (v_{0, x}, v_{0, y}) \). Assuming that only the gravitational force of the earth is present and neglecting the resistance of the air, the projectile follows a parabolic trajectory. Newton’s laws allow to calculate the trajectory from a spatial and temporal point of view. The trajectory is a parabola whose parametric equations are as follows (suppose we shoot the bullet from the coordinate point \((x_{0}, y_{0}) \)):

Some important formulas derived from the equations of motion are the following (we indicate with \(v_{0} \) the modulus of velocity at time \(t = 0 \) and with \(\alpha \) the angle of the initial speed with the abscissa axis \(x \)):

\[ \displaystyle \begin{array}{l} \textbf {horizontal acceleration} = a_{x}=0 \\ \textbf {vertical acceleration} = a_{y}=-g \\ \textbf {horizontal velocity} = v_{x}(t) = v_{0,x} \\ \textbf{vertical velocity } = v_{y}(t) = v_{0,y} – gt \\ \textbf {maximum height} = \dfrac {v_{0}^{2} (\sin \alpha)^{2}}{2g} \\ \textbf {time to return to the ground} = \dfrac {2v_{0}\sin \alpha}{g} \\ \textbf{range} = \dfrac {v_{0}^{2} (\sin 2\alpha)}{g} \\ \end{array} \]**Exercise 2.1**

Prove that, neglecting the air resistance, the maximum range angle for a cannon is \(45^{\circ} \).

## 3) Principles of conservation

It is useful to mention some of the principles of conservation which, in addition to having a profound meaning from the physical point of view, are very useful in solving physics problems.

### 3.1) Principle of conservation of energy

There are different types of energy: kinetic energy, potential energy, thermal energy, nuclear energy, etc. The sum total of all these types of energies remains constant in the universe; energy cannot be destroyed or created, but can only be transformed from one type to another. When studying a physical phenomenon it is useful to divide the universe into two separate parts:

- the system being studied
- the external environment

If these two systems exchange energy or mass then the energy of the system under study may not be conserved.

The principle of energy conservation is a general principle which applies without exception. In mechanical problems a more restricted principle applies, the principle of conservation of mechanical energy, which includes only the types of energy that affect the physical context, kinetic energy and potential energy.

### 3.2) Kinetic energy

Kinetic energy is energy due to the movement of objects. A body of mass \(m \) that moves at speeds of magnitude \(v \) has a kinetic energy given by the following formula:

\[ \text {Kinetic Energy} = K = \frac{1}{2}m v^{2} \]The dimensions of the kinetic energy are \(ML^{2}T^{- 2} \). The unit of measurement in the SI is the **Joule**: \(1\) Joule = \(1 Kg \cdot m^{2} \cdot s^{- 2} \).

### 3.3) Potential energy

Potential energy is a type of energy due to the possibility of doing work by moving a body from one position to another, in the presence of a force field.

A body has potential energy because it can do a work. For example, a body of mass \(m \) which is at height \(h \) above the earth’s surface it transforms its potential energy into kinetic energy, which can be used to do work. Vice versa, to bring a body from the earth’s surface to a height \(h \), some work must be done to win the force of gravity.

The formula for the potential energy of a body of mass \(m \) which is located at height \(h \) from the earth’s surface is as follows:

### 3.4) Mechanical energy

Gravitational force has a very important property: the work done to bring a body from one height to another does not depend on the path, but only on the starting point and the final point. In physics, gravitational force is said to be a **conservative force.****Mechanical energy** \(E \) is defined as the sum of kinetic energy and potential energy:

The **principle of conservation of mechanical energy** states that, in a closed system and in the absence of dissipative forces (such as friction or air resistance), the total mechanical energy in a conservative force field remains constant. So, the potential energy can turn into kinetic energy and vice versa, but the sum of the two remains constant.

### 3.5) Principle of conservation of momentum

Another important physical quantity is the **momentum** (or **quantity of motion**) of a material point of mass \(m \) that moves at speed \(\mathbf{v} \):

It is a vector quantity for which the following **conservation principle** applies: **in an isolated system, the total momentum of a set of material points is conserved.**

For example, in the collision between two material bodies, the total momentum before the impact is equal to the total momentum after the impact.

### 3.6) Impluse and quantity of motion

Another important quantity is the** **impulse** **which a body of mass \(m \) acquires when subjected to a force \(F \) for a certain interval of time \(\Delta t \). We use the symbol \(\mathbf {J} \) to denote the impulse. The fundamental law to remember is expressed by the following formula:

So the impulse applied by a force in the time interval \([t_{1}, t_{2}] \) is equal to the variation of the momentum of the mass \(m \) on which the the force acts.

For a deeper understanding of these fairly complex concepts, you may read the physics texts suggested in the bibliography.

## 4) Unity’s 2D physics engine

Each GameObject that interact in the scene is identified by the cartesian coordinates (x, y, z) in 3D space, or by (x, y) in 2D. To simulate the real world it is necessary to apply the laws of physics to each object and make the necessary calculations to determine speed, acceleration, rotation frequency, result of impacts with other objects, etc.

In the most recent versions of Unity a component has been added to simulate the laws of object physics on the 2D scene, the **Physics2D** engine. Recall that the physical Unity 2D and 3D engines are completely separate. The 3D engine uses the PhysX software product, while the 2D engine uses Box2D.

The parameters of the 2D Physics engine are set using the Physics 2D manager (*Edit -> Project Setting -> Physics2D*).

### 4.1) Components of the 2D physics engine

The main components of Unity’s 2D Physics Engine are illustrated in the following diagram:

### 4.2) The Collider 2D component

In Unity 2D collisions are not controlled directly by the Rigidbody 2D components, but by new components called Colliders 2D. These components define a region of the plane in which interaction between objects can occur. These regions generally have a different shape from the objects themselves, except in the case of simple geometric objects. The main Collider 2D components are shown in the following diagram:

The topic of collisions in two dimensions was illustrated in a previous article in this blog.

### 4.3) The Rigidbody 2D component

The Rigidbody 2D component allows to simulate physical interactions between objects. An object (for example a sprite) with which the Rigidbody 2D component is associated is placed under the control of the 2D physical engine. The Rigidbody 2D component defines physical properties such as gravity intensity, mass, friction, etc. Rigidbody 2D objects can only move in the XY plane and can rotate around the Z axis. There is the possibility of eliminating the effects of gravity for the entire scene (*Edit -> Project Settings -> Physics 2D)*, or for a single object, updating the Rigidbody 2D component.

There are three options for the **Body Type**, which define three different modes of behavior:

- Dynamic
- Kinematic
- Static

The Dynamic option implies that the object moves under the control of the physical engine, according to the properties defined in the Rigidbody 2D component (mass, drag, gravity scale, etc.).

The Kinematic option implies that the object moves in the context of the physical simulation, but control is left to the application. For an object with the Kinematic option, motion is not affected by mass, gravity or other types of forces as it is with the Dynamic option.

With the Static option an object does not move under physical simulation; in a collision it behaves like an object of infinite mass, which does not move.

In the next paragraph we will describe the possibilities that the Rigidbody 2D component offers to simulate the motion of objects in the 2D environment.

### 4.4) Physics Material 2D

Physics Material 2D is a component that can be associated with a GameObject to define the physical characteristics of the object itself. Physics Material contains two properties: **Bounciness** (how much the object bounces after a collision) and **Friction** (friction). A correct choice allows to simulate with more precision the behavior of real objects in physical processes, for example in collisions with other objects.

### 4.5) The Joint type and its properties

Joints 2D are components that allow to define physical constraints between two objects, with varying degrees of freedom. This allows physics to be simulated even for objects made of various components, such as doors, vehicles, complex structures of various types. The main types of joints offered by Unity 2D are illustrated in the following diagram:

**Fixed Joint**– binds two objects rigidly, similar to a parent -> child relationship. The body with the Fixed Joint follows the movements of the other object. In the presence of obstacles, it may happen that it cannot keep the fixed distance but it can assume a behavior similar to a spring**Hinge Joint**– used for example to create a swing door. It is like a hinge joint, like a door hinge**Distance Joint**– allows you to establish a certain distance between two objects**Wheel Joint**– simulates the behavior of a wheel, to allow the creation of vehicles of various kinds**Slider Joint**– allows you to create a sort of track on which a body can slide**Spring Joint**– simulates the behavior of a spring

**How to create a Joint in Unity 2D**

The way to create a Joint is similar for all types; only some specific parameters to be set change. The main steps to define a joint between two objects are the following:

- create an object and assign it the Rigidbody2D component
- assign a physical material to the object
- open the Joints menu (
*Component -> Physics2D*) - choose the type of Joint
- set the parameters in the Inspector
- set the
**Connected Body**field by dragging the second object to be connected

The following animation represents a Spring joint, which simulates the swing of a pendulum:

## 5) Motion with the Unity 2D physics engine

As is known, in Unity the position, rotation and scale information of the objects on the scene are normally managed through the **Transform component** associated with each object.

Using the Rigidbody2D component it is possible to put the objects under the control of the physical engine, which in turn can change the position and speed of the objects themselves. A fundamental task of the Rigidbody2D component is precisely to manage the communication with the Transform component in order to make the position data always updated correctly. The Rigidbody2D component offers some properties and functions that allow you to control the motion of a body, simulating a force applied to the object:

- Rigidbody2D.velocity
- Rigidbody2D.MovePosition
- Rigidbody2D.AddForce, ForceMode2D = Force
- Rigidbody2D.AddForce, ForceMode2D = Impulse

The **AddForce** function accepts two parameters: the first denotes the vector (Vector2D) which represents the applied force and the second denotes the type of thrust (**ForceMode2D**). There are two types of thrusts:

**ForceMode2D.Impulse**(force applied for a short time, for example to make a jump)**ForceMode2D.Force**(it’s a normal force, like pushing to move a wagon or car engine)

The functions that use the physical engine must be put in the FixedUpdate method, since that is the frequency with which Unity updates the calculations for the physics simulation.

### 5.1) Motion with Rigidbody2D.velocity

This function applies an instantaneous speed change of the Rigidbody2D, ignoring its mass.

To understand the difference with AddForce, suppose we have an object that moves in a certain direction. If we apply a force in a direction perpendicular to the direction of motion, the object will not make a sudden change of \(90^{\circ} \), but the change of direction will take place gradually, depending on the intensity of the force. At each time interval, the vector sum is made between the speed vector and the force vector, calculating the new direction of motion. Instead, applying the Rigidbody2D.velocity function, there is an instant change of direction. For example if an object is moving along the positive direction of the \(X \) axis, by executing the following statement:

`rigidbody2D.velocity = Vector2.up;`

we will have a sudden change of motion towards the positive direction of the \(Y \) axis.

The following image illustrates the movement of a ball thrown to hit a target object that moves after each collision. The initial speed is calculated each time, based on the laws of dynamics, to hit the target. The ball is associated with the Rigidbody2D component with the Body Type set to Dynamic.

A rough outline of the instructions for calculating the projectile’s launch speed is as follows:

```
void StartBullet() {
Vector2 m_veloStart = ComputeInitialSpeed(transform.position,
target.transform.position);
m_Rigidbody2D.velocity = m_veloStart;
}
// compute initial bullet speed
public Vector2 ComputeInitialSpeed(Vector2 origin, Vector2 target) {
float gravity = Physics2D.gravity.magnitude;
float distance = Mathf.Abs(target.x - origin.x);
float maxHeight = distance / 4;
float startSpeedY = Mathf.Sqrt(2.0f * gravity * maxHeight);
float time = (startSpeedY + Mathf.Sqrt(startSpeedY * startSpeedY
- 2*gravity * target.y))/gravity;
float startSpeedX = distance / time;
// choose direction
if (target.x - origin.x > 0.0f){
// right direction
return new Vector2(startSpeedX, startSpeedY);
}
// left direction
else {
return new Vector2(-startSpeedX, startSpeedY);
}
}
```

### 5.2) Motion with Rigidbody2D.MovePosition

In addition to the Rigidbody2D.velocity property, there is also another function that you can use to change the position of an object: **Rigidbody2D.MovePosition**. The MovePosition method has a similar effect, except that the Rigidbody2D must be set to Kinematic. In this case the position is updated at each fixed frame and the speed is calculated internally by the physical engine. The MovePosition function is useful for chasing another moving object. The following animation illustrates an object chasing a target that moves in circular motion.

The instructions for chasing the target object are as follows (the “Gravity scale” option is set to zero):

```
private void FixedUpdate() {
Vector2 direction = (target.transform.position -
transform.position).normalized;
if (Vector2.Distance(target.transform.position, transform.position)
> minDist) {
m_Rigidbody2D.MovePosition(m_Rigidbody2D.position + direction
* speed * Time.fixedDeltaTime);
}
else {
Debug.Log("Target catched ");
}
}
```

### 5.3) Motion with Rigidbody2D.AddForce (ForceMode.Force)

With the AddForce function the force is applied during each fixed interval of time (timestep) by the physical engine. The default value is 0.02 seconds, but it can be modified through the editor (*Edit -> Project -> Settings -> Time*).

The AddForce method with the **ForceMode2D.Force** parameter applies a gradual continuous force on the object during the frame period and takes into account the mass.

### 5.4) Motion with AddForce (ForceMode.Impulse)

The AddForce method with the **ForceMode2D.Impulse** parameter applies instantaneous force to the object and takes mass into account. The impulse lasts for the entire frame interval. It is used, for example, to simulate explosions.

For the complete list of properties of the Rigidbody component see the relative section of the Unity manual.

### 5.5) An example of orbital motion with AddForce

In the following animation we simulate the motion of a planet around the sun. The universal gravitation law is applied with appropriate scaling operations of the quantities involved. Both objects have the Rigidbody2D component, with type Dynamic. The Gravity Scale is set to zero.

```
private void FixedUpdate() {
Vector2 appliedForce = Vector2.zero;
Vector2 distance = (target.transform.position - transform.position)
* distanceScale;
float squaredDist = distance.sqrMagnitude;
// use Newton's law of universal gravitation
float gravityForce = G * m_Rigidbody.mass *
m_RigidbodyTarget.mass / squaredDist;
appliedForce = gravityForce * distance.normalized;
m_Rigidbody.AddForce(appliedForce, ForceMode2D.Force);
}
```

## 6) 2D rotations

Finally, we mention another function made available to rotate the plane: **RigidBody2D.AddTorque.** Torque is the moment that a force exerts on a body with respect to a reference point. The moment of a force applied to a material point which is in the position \(P \), with respect to an initial point \(O \), is defined with the vector product:

where \(\mathbf {r} \) is the radius vector \(\mathbf {OP} \) that goes from the origin point \(O \) to the position \(P \) where the material point is located. The moment vector is perpendicular to the plane formed by the position vector and the force vector. The intensity of the torque vector is

\[ |\mathbf{M}| = |\mathbf{r} \times \mathbf{F}|= rF \sin \theta \]

The moment is the cause of the rotation of a body. The topic of rotations in the plane will be discussed in a subsequent article.

## Conclusion

Many video games for mobile or even desktop devices are still developed in the 2D environment. It’s therefore important to know the features that the Unity platform offers, and among these in particular the potential of the 2D Physics Engine to simulate motion and collisions between objects.

## Bibliography

^{[1]}Halliday, Resnick – Fundamentals of Physics (Wiley)

^{[2]}R. Feynman – The Feynman Lectures on Physics (Basic Books)

## 0 Comments