惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

M
MIT News - Artificial intelligence
有赞技术团队
有赞技术团队
S
Schneier on Security
aimingoo的专栏
aimingoo的专栏
T
Troy Hunt's Blog
U
Unit 42
Hacker News - Newest:
Hacker News - Newest: "LLM"
V2EX - 技术
V2EX - 技术
T
The Blog of Author Tim Ferriss
V
Visual Studio Blog
H
Heimdal Security Blog
H
Hacker News: Front Page
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Cloudbric
Cloudbric
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
The Cloudflare Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
MyScale Blog
MyScale Blog
F
Fortinet All Blogs
N
News | PayPal Newsroom
Attack and Defense Labs
Attack and Defense Labs
D
DataBreaches.Net
N
News and Events Feed by Topic
Security Archives - TechRepublic
Security Archives - TechRepublic
Forbes - Security
Forbes - Security
Simon Willison's Weblog
Simon Willison's Weblog
F
Full Disclosure
The Register - Security
The Register - Security
L
LINUX DO - 热门话题
Webroot Blog
Webroot Blog
Google Online Security Blog
Google Online Security Blog
AI
AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
Intezer
S
Security Affairs
阮一峰的网络日志
阮一峰的网络日志
K
Kaspersky official blog
云风的 BLOG
云风的 BLOG
博客园 - 叶小钗
T
Threatpost
Spread Privacy
Spread Privacy
小众软件
小众软件
AWS News Blog
AWS News Blog
S
Secure Thoughts
S
Security @ Cisco Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks

Martin Heinz's Blog

A Guide to Python's Weak References Using weakref Module Recent Docker BuildKit Features You're Missing Out On Modern Git Commands and Features You Should Be Using Everything You Can Do with Python's textwrap Module Monitoring Indoor Air Quality with Prometheus, Grafana and a CO2 Sensor Everything You Can Do with Python's bisect Module You Don't Need a Dedicated Cache Service - PostgreSQL as a Cache A Collection of Docker Images To Solve All Your Debugging Needs Weird Python "Features" That Might Catch You By Surprise Lessons Learned From Writing 100 Articles Debugging Crashes and Deadlocks in Python using PyStack Goodbye etcd, Hello PostgreSQL: Running Kubernetes with an SQL Database Remote Interactive Debugging of Python Applications Running in Kubernetes The Right Way to Run Shell Commands From Python Real Multithreading is Coming to Python - Learn How You Can Use It Now Python's Missing Batteries: Essential Libraries You're Missing Out On Kubernetes-Native Synthetic Monitoring with Kuberhealthy Make Your CLI Demos a Breeze with Zero Stress and Zero Mistakes Reduce - The Power of a Single Python Function Why I Will Never Use Alpine Linux Ever Again Cgroups - Deep Dive into Resource Management in Kubernetes Dictionary Dispatch Pattern in Python Boost Your Python Application Performance using Continuous Profiling Lazy Evaluation Using Recursive Python Generators Python Magic Methods You Haven't Heard About Getting Started with Mastodon API in Python Backup-and-Restore of Containers with Kubernetes Checkpointing API Getting Started with Google APIs in Python Python CLI Tricks That Don't Require Any Code Whatsoever All The Ways To Introspect Python Objects at Runtime What is Python's "self" Argument, Anyway? Python List Comprehensions Are More Powerful Than You Might Think You Should Be Using Python's Walrus Operator - Here's Why Recipes and Tricks for Effective Structural Pattern Matching in Python It's Time to Say Goodbye to These Obsolete Python Libraries Advanced Features of Kubernetes' Horizontal Pod Autoscaler Data and System Visualization Tools That Will Boost Your Productivity Stop Messing with Kubernetes Finalizers Automate All the Boring Kubernetes Operations with Python End-to-End Monitoring with Grafana Cloud with Minimal Effort Bitly | bit.ly/3JLmSgA Bitly | bit.ly/3uETfbi Bitly | bit.ly/3MI4Iz0 Bitly | bit.ly/3M30D82 Bitly | bit.ly/3oMJ6qR Bitly | bit.ly/3IRD7IK Bitly | bit.ly/3A3B69t Bitly | bit.ly/31lKCYA Bitly | bit.ly/30uviIM Bitly | bit.ly/3E1X2mw Bitly | bit.ly/3Dv7JxP Bitly | bit.ly/3GG1BEz Bitly | bit.ly/3lLavs4 Bitly | bit.ly/39TqP3m Bitly | bit.ly/3A5Mpx8 Bitly | bit.ly/3kGwPl4 Bitly | bit.ly/3iHtulU Bitly | bit.ly/3xGjtKS Bitly | bit.ly/3h8DZg0 Bitly | bit.ly/2RQn1dG Bitly | bit.ly/3p2B5wW The Easiest Way to Debug Kubernetes Workloads Bitly | bit.ly/2PHVudx Cloud Native CI/CD with Tekton - Building Custom Tasks Bitly | bit.ly/3dg3QR9 Bitly | bit.ly/3qHtSkZ Deep Dive into Docker Internals - Union Filesystem Bitly | bit.ly/3qlRAUN Bitly | bit.ly/3pCUJ26 Bitly | bit.ly/3ifZxYr Bitly | bit.ly/34ZhIMt Bitly | bit.ly/3qSO7h0 Bitly | bit.ly/3muGLOk Bitly | bit.ly/35xN79v Bitly | bit.ly/3mLGshK Bitly | bit.ly/2IvkGQl Bitly | bit.ly/2Sk1KFK Bitly | bit.ly/3iCNIL6 Bitly | bit.ly/3beQPpy Saving Your Linux Machine from Certain Death New Features in Python 3.9 You Should Know About Deploy Any Python Project to Kubernetes Analyzing Docker Image Security Recursive SQL Queries with PostgreSQL Automating Every Aspect of Your Python Project Tour of Python Itertools Ultimate Setup for Your Next Python Project Making Python Programs Blazingly Fast Security and Cryptography Mistakes You Are Probably Doing All The Time Going Serverless with OpenFaaS and Golang - Building Optimized Templates Going Serverless with OpenFaaS and Golang - The Ultimate Setup and Workflow Setting Up Swagger Docs for Golang API Building RESTful APIs in Golang Pytest Features, That You Need in Your (Testing) Life Setting up GitHub Package Registry with Docker and Golang Ultimate Setup for Your Next Golang Project Python Tips and Trick, You Haven't Already Seen, Part 2. Tricks for Postgres and Docker that will make your life easier Getting The Most Out of Reading Books - Reading The "Professional Way" Python Tips and Trick, You Haven't Already Seen
Implementing 2D Physics in Javascript
Martin · 2020-02-02 · via Martin Heinz's Blog

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!

physics showcase

You can checkout 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:


function move(dt) {
    x += vx * dt;
    y += vy * dt;
}

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 timer, which in 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):


x = 150 += -1 * 0.1 -> 149.9
y =  50 +=  1 * 0.1 -> 50.1

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


function move(dt) {
    vx += ax * dt;
    vy += ay * dt;
    x += vx * dt;
    y += vy * dt;
}

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 change in velocity or speed (vx/vy), which we then use to move objects like before. Now, if we copy previous example and add acceleration only on x axis (going west), we get:


vx =  -1 += -1   * 0.1 ->  -1.1  // vx += ax * dt;
vy =   1 +=  0   * 0.1 ->   1    // vy += ay * dt;
 x = 150 += -1.1 * 0.1 -> 149.89 //  x += vx * dt;  Moved further (-0.01) than in previous example!
 y =  50 +=  1   * 0.1 ->  50.1  //  y += vy * dt;

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:

gravity

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

Equation of force:


F = m * a    ... Force is Mass times Acceleration
a = F / m    ... From that we can derive that force acting on some object (mass) accelerates

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

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

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

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

We then break it down into vectors:

Finally we get F:

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. 🙂


function moveWithGravity(dt, o) {  // "o" refers to Array of objects we are moving
    for (let o1 of o) {  // Zero-out accumulator of forces for each object
        o1.fx = 0;
        o1.fy = 0;
    }
    for (let [i, o1] of o.entries()) {  // For each pair of objects...
        for (let [j, o2] of o.entries()) {
            if (i < j) {  // To not do same pair twice
                let dx = o2.x - o1.x;  // Compute distance between centers of objects
                let dy = o2.y - o1.y;
                let r = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
                if (r < 1) {  // To avoid division by 0
                    r = 1;
                }
                // Compute force for this pair; k = 1000
                let f = (1000 * o1.m * o2.m) / Math.pow(r, 2);
                let fx = f * dx / r;  // Break it down into components
                let fy = f * dy / r;
                o1.fx += fx;  // Accumulate for first object
                o1.fy += fy;
                o2.fx -= fx;  // And for second object in opposite direction
                o2.fy -= fy;
            }
        }
    }
    for (let o1 of o) {  // for each object update...
        let ax = o1.fx / o1.m;  // ...acceleration
        let ay = o1.fy / o1.m;

        o1.vx += ax * dt;  // ...speed
        o1.vy += ay * dt;

        o1.x += o1.vx * dt;  // ...position
        o1.y += o1.vy * dt;
    }
}

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:

header

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


class Collision {
    constructor(o1, o2, dx, dy, d) {
        this.o1 = o1;
        this.o2 = o2;

        this.dx = dx;
        this.dy = dy;
        this.d = d;
    }
}

function checkCollision(o1, o2) {
    let dx = o2.x - o1.x;
    let dy = o2.y - o1.y;
    let d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
    if (d < o1.r + o2.r) {
        return  {
            collisionInfo: new Collision(o1, o2, dx, dy, d),
            collided: true
        }
    }
    return  {
        collisionInfo: null,
        collided: false
    }
}

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 sum of their radii is lower than their distance d, then they must be in collision so we return new Collision object.

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


n_x = d_x / d        ... this is eigenvector
n_y = d_y / d

s = r_1 + r_2 - d  ... s is size of collision (see picture)

So, in JavaScript code that would be:


function resolveCollision(info) {  // "info" is a Collision object from above
    let nx = info.dx /info.d;  // Compute eigen vectors
    let ny = info.dy /info.d;
    let s = info.o1.r + info.o2.r - info.d; // Compute penetration depth
    info.o1.x -= nx * s/2;  // Move first object by half of collision size
    info.o1.y -= ny * s/2;
    info.o2.x += nx * s/2;  // Move other object by half of collision size in opposite direction
    info.o2.y += ny * s/2;
}

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

Solving Collisions with Force

Aaaaand final piece of 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 law of momentum conservation and law of energy conservation which helps us build and solve following magical equation:


k = -2 * ((o2.vx - o1.vx) * nx + (o2.vy - o1.vy) * ny) / (1/o1.m + 1/o2.m) ... *Magic*

Well, how does this magical k help us? We know 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:

And now the final code:


function resolveCollisionWithBounce(info) {
    let nx = info.dx /info.d;
    let ny = info.dy /info.d;
    let s = info.o1.r + info.o2.r - info.d;
    info.o1.x -= nx * s/2;
    info.o1.y -= ny * s/2;
    info.o2.x += nx * s/2;
    info.o2.y += ny * s/2;

    // Magic...
    let k = -2 * ((info.o2.vx - info.o1.vx) * nx + (info.o2.vy - info.o1.vy) * ny) / (1/info.o1.m + 1/info.o2.m);
    info.o1.vx -= k * nx / info.o1.m;  // Same as before, just added "k" and switched to "m" instead of "s/2"
    info.o1.vy -= k * ny / info.o1.m;
    info.o2.vx += k * nx / info.o2.m;
    info.o2.vy += k * ny / info.o2.m;
}

Conclusion

This post includes lots of math, but most of it is pretty simple, so I hope this helped you understand and familiarize yourself with these physical concepts. If you want to see more details, then you can check out code in my repository here and interactive demo here.