How to create a Simple Physics Engine - Part 1
We use physics, we see physics in action, we experience physics in everything we do in our day-to-day life. How do you add physics to your code and make your code also experience nature's forces? That's what I'll be explaining to you on the article about physics engine.
Karthik Kamalakannan
Founder and CEO
We use physics, we see physics in action, we experience physics in everything we do in our day-to-day life. How do you add physics to your code and make your code also experience nature’s forces? That’s what I’ll be explaining to you on the article about physics engine.
What is a physics engine?
It’s nothing too complex. It’s a collection with all the physics related functions in it.
What does a physics engine do?
A physics engine simulates physics to objects in any code.
What do you need to code a physics engine?
The answer is Math
Yes, all you need to know is basic Math and some simple physics terms and you’re on your way to create your first Physics engine.
Let’s start with the basics of it. Imagine you’re creating a scene where you want your object [Let’s imagine a ball] to react with another object [Let’s imagine a wall].
Well, the most obvious way to achieve that would be hard coding it. But where is the fun in that, huh? :D
We need our elements to interact with everything we throw at them.
It could be a feather, a rock, an elephant, any object basically… okay, I might sound a little carried away with all this. So, let’s just get on with it and show how you can build your very own physics engine.
Things you will need to get started:
- A Code Editor
- Physics Equations
1. Code Editor
We will be coding in javascript and all these animations is better using a Canvas if we use JS. So, the best library to use for these would be p5.js.
p5 is a simple and amazing javascript library which has all the functions to draw, move or do whatever you want to do with your code elements in the most simplest way. Here is a great resource you can use to get started with p5.
Moving on, we will start with the setup of the code editor.
Step 1: Go to https://editor.p5js.org/ (SignUp or Login if you already have an account) and starting coding in the workspace.
Step 2: Aaand we are done. That’s it.
2. Physics Equations
Hope you guys still have your school physics books lying around. We can also refer wikipedia for any physics formula we want. For this part, we will talk about simple concepts like motion. Since we are using a web editor, we don’t need to set anything up. p5.js web editor will take care of everything.
p5.js also follows the same javascript coding convention. So, if you are familiar with web-concepts, then hurrah!, you’re almost there.
For the people who are new, let me take you through a quick walk through of the editor.
This is the editor. It is divided into two halves. The coding-workspace and the preview area. (Don’t worry if your screen looks different. I have just changed my theme).
Let’s start with the elements you see on your editor, that’d be the
- Menubar
- Start and Stop
- Auto refresh
- Name
- Settings
- Project Folder
- Coding space
- Preview
Menubar:
A standard menu bar as you would see on any other editor. For now we need to know the File -> New. This will create a new Project.
Start and Stop:
Start button will compile and run your code and preview it on the preview tab. Stop will stop the compilation.
Auto-refresh: [Not recommended]
Although I don’t use auto-refresh, it might be handy to other people. Auto refresh refreshes the preview if you change your code while you are running it.
Name:
The name of your project. p5 editor will provide funny random names which you may choose to keep or can change according to your needs.
Settings:
You guessed it, all the little tweaks are available under the settings for you to make the editor your own.
Project Folder:
All your project files are placed under your project folder. You can add another folder if you need to, but for now let’s make this simple and stick to just adding a file.
Coding space:
Here is where all the magic happens. All your code and logic will churn together to form a masterpiece.
Preview:
Here is where you will get to see your masterpiece come to life.
Before we go further, let us discuss the 3 default files under the project folder
index.html - This is the starting of the webapp. This is where you will link your script (JS) files and style(CSS) files.
style.css - This is known as the stylesheet where you will modify all the style property of any element that is used in the html file or in the js file.
sketch.js - This the one we are interested in and the one we will be programming more into and this is basically the starting point of our canvas.
By default, sketch.js will provide you with a boilerplate template to get you started.
Let’s decrypt what each one means.
1. setup( )
The setup function is called once at the beginning of the code compilation.
createCanvas creates a canvas in the preview for the specified width and height.
2.draw( )
The draw function is called for every timestamp in the canvas or the body of the element. Draw function is especially useful when updating any changes to the objects.
Let’s start with our first example.
- Start with a new project
- Select Sketch -> Add File . This will prompt you a file name. Enter a “Ball” as the filename and you will see your file listed under the project folder.
- Let’s add some code to our Ball.js.
What’s going on here? Confusing right? Let me explain what’s going on here .
We have just created a class Ball with some functions for the class Ball. Pretty simple right. And don’t get confused with all the mathematics.
We have used a constructor to just create 2 vectors. A vector in math is nothing but an object with an x and y value. Just like the points you used to plot on a graph, we will draw our objects with respect to a coordinate system.
In this case, we will create a location vector which will keep track of our object’s location relative to the canvas and we will create another vector for the velocity which will keep track of how fast the object is moving, because velocity is how fast you are moving, right?
Let’s display our Ball object on the canvas. We will create a user defined function called display and then draw an ellipse. ellipse is a predefined shape of p5.js. We want a circle so we pass the same radius for the ellipse. We will display our ellipse using the location vectors we created in the constructor function.
Let’s move the ball object with respect to its velocity. So any object with a location x1, y1 to reach another location x2, y2 has to move with some velocity to reach x2, y2. So we will add a constant velocity to the location vector. So for every timestamp we will get a new location that is the sum of the last location and the velocity.
Let’s just add this bounce function to make things a little more interesting. All it does is look for the canvas boundaries and keeps the ball inside the canvas.
When a ball hits a wall in real life, the wall will exert an equal force on the ball, but since the ball is way way lighter than the wall, it will move or bounce back and the wall stays .
In code we can’t make the boundary push the ball, so instead we will negate the velocity of the ball so that it moves in the opposite direction whenever it touches any boundary. Damn simple right.
Now let’s just add some code to our sketch.js
Let’s create a ball variable to create an instance of the Ball class in the setup function. Now ball variable can access all the functions that Ball Class has.
For every draw loop, the ball is moved, ball object checks for bounce and changes the location and then ball object is displayed at the location in the loop timestamp.
And it’s over right? Click on the Run button and everything starts? Right?
NOPE!!! Here’s where the common mistake occurs for every programmer. Even I have spent hours of my time looking for why it doesn’t run. Here’s the reason.
Never forget to add your js file under script in the index.html.
Now you’re ready!!! Go ahead and click the Run button and there you go, you have your first physics simulated program.
Here’s what you will see:
And there you have it, your first physics engine. In the upcoming steps we will talk about how to make it look more realistic. Go ahead and try playing with the values.