Implementing 2D Physics in Javascript

栏目: IT技术 · 发布时间: 4年前

内容简介:Let’s have some fun with JavaScript while implementing realistic 2D physics simulations and visualization!Physics and implementations of real looking animations might seem very complex and difficult, but it’s actually not the case. These algorithms can be

Implementing 2D Physics in JavaScript

Let’s have some fun with JavaScript while implementing realistic 2D physics simulations and visualization!

Feb 1 ·5min read

Implementing 2D Physics in Javascript

Photo by Mohdammed Ali on Unsplash

Physics and implementations of real looking animations might seem very complex and difficult, but it’s actually not the case. These algorithms can be very simple and can produce realistic simulations of various physics concepts, including velocity, acceleration or gravity.

So, let’s see how those algorithms work while implementing 2D physics simulation in JavaScript!

Implementing 2D Physics in Javascript

You can check out the animations and examples here: https://martinheinz.github.io/physics-visual/

TL;DR: Source code is available in my repository here: https://github.com/MartinHeinz/physics-visual

Uniform and Accelerated Movement

Let’s start with the most basic thing — moving stuff around.

If we want just uniform movement, then we can use code like this:

In the code above x and y are coordinates of an object, e.g ellipse, next vx and vy are velocities in horizontal and vertical axis respectively and dt (time delta) is a time between 2 ticks of a timer, which in the case of JavaScript are 2 calls to requestAnimationFrame .

As an example — if we wanted to move object sitting at (150, 50) and moving southwest, then we would have the following (movement after single tick):

Moving uniformly is pretty boring though, so let’s accelerate the movement of our objects:

In this piece of code we added ax and ay which represent acceleration on x and y axis respectively. We use the acceleration to calculate the change in velocity or speed ( vx/vy ), which we then use to move objects like before. Now, if we copy the previous example and add acceleration only on x-axis (going west), we get:

Gravity

Now that we can move things around, how about moving objects towards other objects? Well, that’s just called gravity . What do we need to add, to implement that?

Just so you know what we are trying to get to:

Implementing 2D Physics in Javascript

First things first, let’s recall a few equations from high school:

Equation of force :

If we now want to extend this to force of 2 objects acting on each other, we get:

Implementing 2D Physics in Javascript
Force EQ

It’s getting little complicated (for me at least), so let’s break it down. In this equation |F| is the magnitude of force, which is same for both objects, just in the opposite direction. These objects are represented by their mass - m_1 and m_2 . k here is a gravitational constant and r is the distance of centers of gravity of these object. If it still doesn't make much sense, then here's a picture:

Implementing 2D Physics in Javascript
Objects Pulling

If we want to create some visualization we will end up with more than 2 objects, right? So, what happens when we have more objects acting on each other?

Implementing 2D Physics in Javascript

Forces with Multiple Objects

Looking at the picture above, we can see 2 orange objects pulling black one with forces F_1 and F_2 , what we are interested in though is final force F , which we can calculate like this:

  • We first calculate forces F_1 and F_2 using equations from above
Implementing 2D Physics in Javascript
  • We then break it down into vectors:

Alright, we have all the math we need, now how will the code look? I will spare you all the steps and just show you final code with comments, if you need more information, feel free to reach out to me.

Collisions

When things move around they will also collide at some point. We have two options for solving collisions — push objects out of collision or bounce away, let’s look at the pushing solution first:

Implementing 2D Physics in Javascript

Before we can resolve collision we need to first check whether 2 objects are actually colliding:

We first declare Collision class which represents 2 colliding objects. In the checkCollision function we first compute x and y components of distances of objects and then compute their actual distance d . If the sum of their radii is lower than their distance d , then they must be in collision so we return new Collision object.

Implementing 2D Physics in Javascript

Collision

Now, to resolve their collision, we need to know the direction of displacement and it’s magnitude :

Implementing 2D Physics in Javascript

Movement After Collision

So, in JavaScript code that would be:

You can view an interactive example of this collision resolution at https://martinheinz.github.io/physics-visual/ (Click on Pushing Through Objects )

Solving Collisions with Force

Aaaaand the final piece of the puzzle — resolving collisions by bouncing objects. In this case, it’s better to omit all the math as it would make the article twice as long, so all I’m gonna tell you is that we need to account for the law of momentum conservation and the law of energy conservation which helps us build and solve following magical equation:

Well, how does this magical k help us? We know the direction in which the objects will move (we can compute that using eigenvectors like before with n_x and n_y ), but we don't know by how much and that's the k . So, this is how we compute vector ( z ), that tells us where to move those objects:

Implementing 2D Physics in Javascript

Momentum

And now the final code:


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Google總部大揭密

Google總部大揭密

史蒂芬.李維 / 陳重亨 / 財信 / 2011-11

∣如果有一天,Google的搜尋引擎突然故障 ∣GMAIL信件全數消失 ∣Google Maps、Google Docs、Google行事曆等所有雲端服務全面停擺 ∣我們該怎麼辦?! 歷史上像Google如此成功,且廣受推崇的企業可沒幾家。它改變了網路的使用方式,也成了我們生活不可或缺的一部分。這到底是怎麼辦到的? 《連線》雜誌資深主筆史蒂芬.李維史無前例同時取得LS......一起来看看 《Google總部大揭密》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码