1. Code
  2. Games

Gravity in Action

Read Time:11 minsLanguages:
This post is part of a series called You Do The Math.
Euclidean Vectors in Flash
Hit the Target With a Deadly Homing Missile

The study of forces is of central interest in dynamics, the study of causes of motion and changes in motion. Gravitational force is one example; it is this which causes satellites to revolve around planets and us to stay on the ground.

In this tutorial, we will build a simulation of such phenomenon and be able to observe, experiment and play with particles on the scene.

Among all particles generated, one main particle will attract others. As these particles move towards the main one, users can click on this main particle to drag it around, causing these particles to redirect their course. These particles will stop moving as they collide with the edge of main ball, but they won't overlap each other.

The structure of this tutorial is arranged in a manner where a brief theory in Physics in delivered before introducing the implementation of the simulation. Enjoy!

Final Result Preview

Let's take a look at the final result we will be working towards:

Click and drag the big green circle to move it around, and watch how the little blue circles react.

Step 1: Gravitational Force, Formula

Formula of attractive forceFormula of attractive forceFormula of attractive force

First, a Physics preface. The attractive gravitational force between any two objects is expressed through the following formula:

F: attractive force being exerted onto object of interest (p2) by
an arbitrary particle (p1).

G: Gravitational constant

m1: mass of p1

m2: mass of p2

r: distance between p1 and p2

Take special note of the following:

  1. The relationship between gravity and distance: F is inversely proportional to the square of the distance separating the two particles. This means the closer A and B are to each other, the higher the attractive force between them and vice versa. If you double the distance, the force goes down to a quarter of its original value.
  2. Value of gravitational constant, G, is scientifically 6.67259 x 10-11 N * m2 / kg2. However, 500 will substitute this value in Flash environment.
  3. We can relate particle’s width to their mass. For this example, I’ve defined a particle’s mass to be half of its radius.

Step 2: Newton's 2nd Law, Equation

In order to translate force into kinematics, we need to calculate particle’s acceleration. The famous equation by Sir Isaac Newton is shown below:

formula f=maformula f=maformula f=ma

F: gravitational force being exerted onto object of interest (p2)

m: mass of object of interest (p2)

a: acceleration of object of interest (p2) under influence of F

Here, the implication is that a higher force applied onto particle A results in a higher acceleration (assuming its mass stays the same). This acceleration will change the particle’s velocity.

Step 3: Starting Project

Implementation will be done in FlashDevelop IDE. Build your project file.

  1. Start a new Project, PROJECT > NEW PROJECT…
  2. Select from pop up window, AS3 PROJECT
  3. Name your project. In my case, Attractor
  4. Select your project location

See this guide for an introduction to FlashDevelop.

Step 4: Classes You Need

There are 4 classes to create in folder \src\:,, & It is advisable that you download all these files from the source package and try to map them against steps to come to get a general understanding of the mechanism before modifying them. Their roles are expressed as below:

Class Name Purpose of Organisation Class to create the balls visually and to attach animation to events.
Vector2D Class that holds all vector manipulation functions.
Ball Class that contains functions to visually generate a ball, implements dynamics and kinematics of a ball.
Math2 Static class that holds a function to facilitate randomizing the initial location of balls.

Step 5: Randomising Values

Lets talk about the Math2 class first. The function below will help to generate a random number within the specified range. Accepts two inputs, minimum limit and maximum limit in range.

Step 6: Vector2D, Getters and Setters

The bulk of Math used is located in Vector2D. This tutorial assumes a level of familiarity in vector analysis in the users. The functions below are generally used to get and set vector components, plus a method to reset all components to zero. In any case, if you are uncomfortable with Vectors, visit a great post on Euclidean Vectors by Daniel Sidhion.

Step 7: Vector2D, Operations

The major uses of Vector2D lie in the following functions, which:

  • obtain the magnitude of vector
  • obtain the angle made by vector in relation to the origin
  • obtain the vector direction of vector
  • perform simple vector operations of addition, subtraction and scalar

Step 8: Drawing

The Ball class is where all the interesting operations take place. To begin our animation, we need to draw a ball and set several kinematics- and dynamics-related variables. The function to draw a ball is as below:

Step 9: Private Variables

The mentioned several kinematics and dynamics related variables are stated as below:

Step 10: Initiation

As the constructor of Ball class is called, graphics is drawn. Once drawn, the ball will be placed on the stage randomly. We will also set the private variables. All vector quantities will also be initialized at 0, except for the displacement which is measured relative to origin.

Step 11: Calculate Attractive Force

We need to calculate the underlying force that causes our particles to animate. Guess what, it's the gravitational force. The function below will help in calculating this force. Note that a cap is applied on the acceleration at 5. The horizontal and vertical components of force are derived using trigonometry; the animation above may help in understanding the mathematics of this.

Step 12: Calculate Acceleration

Once force vector has been obtained, we can calculate the resulting acceleration. Remember, F = ma, so a = F/m.

Step 13: Calculate Displacement

With acceleration calculated, we can effectively calculate the resulting displacement.

Remember that force calculated is actually based upon the displacement between the center of the balls.

Step 14: Implement Displacement

Then, we are able to move our ball to its new location, through the function below. Note that displacement calculated is never implemented onto the ball's current location straightaway. Such design is to allow checking be done: collision detection between balls.

Remember, the force is based upon distance between centers. Therefore, the balls will penetrate and continue moving due to attractive force being higher when they are closer. We need to reset acceleration and velocity to 0 when the balls touch one another’s edge. However, we need to obtain a means of detecting the collision between two balls.

Step 15: Collision Detection

Collision can be easily checked. Separation between any two balls should not be less than the sum of their radii. Here’s the collision detection function:

Step 16: Calculate Displace to Repel

Calculate displacement to repel so that two overlapping balls are placed side by side without overlapping.Calculate displacement to repel so that two overlapping balls are placed side by side without overlapping.Calculate displacement to repel so that two overlapping balls are placed side by side without overlapping.

Usually when collision has been detected between two balls, their state is overlapping each other. We need to make sure that they will just sit nicely on the edge and not overlap. How? We can displace one of the balls away from the other, but we need to calculate the right displacement to adjust first. Here’s the displacement calculation:

Step 17: Implement Displacement to Repel

Implementing repelling displacement onto a ballImplementing repelling displacement onto a ballImplementing repelling displacement onto a ball

After we have calculated the right displacement, we need to implement it. The action is like repelling one of the balls. In addition, we need to do another two extra commands. Remember, we are dealing with a dynamic environment. Even after we have set the displacement one of the ball to the edge, acceleration due to force and the resulting velocity will animate it, causing an undesirable movement of jerking in and out. We need to reset these values of acceleration and velocity to zero.

Step 18: Animate

Finally, we can animate (render) our ball as if it were being attracted by another. When collision is detected, displacement will be adjusted so that it will not penetrate the edge. This will happen first for the balls when they collide with center, and then for the balls when they collide with one another.

Step 19: Private Variables

Moving on to our last class, Main. Main class is generated at the start of the project. Private variables will include the one ball that attracts all the others and the number of balls in our Flash presentation.

Step 20: Draw Balls

First of all, we should initialize balls. There will be one main ball that attract all the others. The others are named so that referencing can be easily done later.

Step 21: Implement Ball Interaction

Then, assign events to the main ball to make it draggable when clicked and stop when released.

Step 22: Animate Balls

Animating balls that are being attracted by the main. An EnterFrame event is assigned to each ball.

Step 23: Test Movie

Finally, press Ctrl + Enter to preview the animation.


To bring this tutorial one step further, readers may extend this project by implementing other linear forces.

In any case, simulations serve as a great tool in delivering ideas difficult to explain by plain text and image in a Physics classroom environment, especially when the state changes over time.

I hope this little tutorial helps you in some way. Terima kasih (that is "thank you" in Malaysia) for taking time to read and looking forward to hearing comments from fellow readers.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.