[HN Gopher] Build a simple 2D physics engine for JavaScript game...
       ___________________________________________________________________
        
       Build a simple 2D physics engine for JavaScript games (2012)
        
       Author : WoodenChair
       Score  : 119 points
       Date   : 2022-08-24 08:09 UTC (14 hours ago)
        
 (HTM) web link (developer.ibm.com)
 (TXT) w3m dump (developer.ibm.com)
        
       | bewuethr wrote:
       | This reminds me of the little platformer that you build in
       | _Eloquent JavaScript_ , first with HTML elements[1][2], then with
       | Canvas[3][4].
       | 
       | [1]: https://eloquentjavascript.net/16_game.html
       | 
       | [2]: https://eloquentjavascript.net/code/#16
       | 
       | [3]: https://eloquentjavascript.net/17_canvas.html
       | 
       | [4]: https://eloquentjavascript.net/code/#17
        
       | naillo wrote:
       | For a more modern approach (that's one of those rare cases where
       | things have gotten more powerful while getting simpler over the
       | years): https://www.youtube.com/c/TenMinutePhysics/videos (by
       | basically the inventor of PBD, which he barely even
       | mentions/brags about).
        
         | ArtWomb wrote:
         | I've been experimenting with webgl ragdoll physics based
         | loosely on Takahiro Harada's GPU Gems article, but I'm nowhere
         | near the "puppetmaster" stage yet ;)
         | 
         | https://developer.nvidia.com/gpugems/gpugems3/part-v-physics...
        
         | antegamisou wrote:
         | Big props to Matthias Muller-Fischer for his seminal work in
         | physical simulation.
         | 
         | https://scholar.google.com/citations?user=HZwexAQAAAAJ
        
           | meheleventyone wrote:
           | Yup I've written a few toy physics sims based on his work.
           | Super prolific and amazingly elegant approaches.
        
         | rando14775 wrote:
         | What is PDB?
        
           | naillo wrote:
           | Position based dynamics :) With normal `next_pos =
           | current_pos + velocity * dt` schemes you can get
           | instabilities and it can be non obvious how to implement
           | certain physics phenomena. With PBD you basically define a
           | 'constraint' that particles have to satisfy (e.g. rigid
           | lengths become a 'distances between points must be X') and
           | then you solve for a valid configuration in between renders
           | (basically with gradients descent, though you solve for roots
           | so it becomes newtons method).
        
             | meheleventyone wrote:
             | Paper for the extended version here, linking to this one
             | because the extension solves some issues and isn't that
             | much more complex: https://matthias-
             | research.github.io/pages/publications/XPBD....
             | 
             | For a more lay explanation you solve constraints directly
             | by moving elements around and using the difference between
             | their current position and previous position as their
             | velocity. If you've some experience of numerical
             | integration it's quite similar to verlet integration. This
             | approach is good because it lets you have constraints with
             | infinite stiffness without the simulation exploding.
             | 
             | The original papers consider points (like a mass-spring
             | system) but it's also been extended to rigidbodies.
        
               | naillo wrote:
               | Good survey on many other extensions too:
               | http://mmacklin.com/2017-EG-CourseNotes.pdf
        
               | zokier wrote:
               | How does PBD compare to IPC[1] derived methods, like
               | affine body dynamics[2] that I happened to notice in the
               | latest siggraph papers?
               | 
               | [1] https://ipc-sim.github.io/ (see related projects
               | section at bottom)
               | 
               | [2] https://arxiv.org/abs/2201.10022
        
             | breck wrote:
             | Interesting! This makes sense to me.
             | 
             | I'm new to physics engines--I just started figuring out how
             | to upgrade my simple grid cellular automata engine to a 2D
             | engine for my toy sim tool
             | (https://github.com/breck7/simoji) --and have been
             | surprised by existing implementations, because it just
             | seems not how the universe actually computes. I had not
             | seen PBD before and it seems to be a closer model.
        
               | naillo wrote:
               | You should check out taichi: https://github.com/taichi-
               | dev/taichi They have a ton of great demos for doing
               | physics but check out this example in particular for
               | something related to your project:
               | https://github.com/taichi-dev/quantaichi#game-of-life-
               | gol. (Taichi also makes it super easy to write things for
               | the GPU and the kernels are differentiable :).)
        
       | demoapple wrote:
        
       | appletest wrote:
        
       | trinovantes wrote:
       | IBM is probably the last place I expect to find a game dev
       | tutorial
       | 
       | Are they trying to mimic Digital Ocean's docs to promote their
       | brand?
        
         | samwillis wrote:
         | > Updated 19 November 2012 | Published 20 November 2012
         | 
         | Not only is this an old post published just after DO lunched -
         | but it apparently was updated before it was published...
         | 
         | Anyone who was new to JS in the last five years is going to see
         | the older syntax in this post and be like "what 'prototype'?
         | Why aren't they using 'let' and 'const'? Why aren't they using
         | forEach to loop through that array? Why isn't this in
         | TypeScript?"...
        
           | Kiro wrote:
           | Maybe it's not true anymore but forEach used to be much
           | slower, which matters when you make a game engine and need to
           | iterate lists at least 60 times a second.
        
           | mvladic wrote:
           | Why would they use forEach? Is that criteria that your code
           | is more modern? Or by forEach you mean: "for (const entity of
           | entities) {...}"?
        
             | samwillis wrote:
             | forEach landed in Chrome in 2014 after this post, at the
             | same time as for...of. True that forEach was available in
             | some browsers earlier than that and could be polyfilled.
             | Which do I mean? either.
        
               | jsgamedevthrow wrote:
               | I have no idea what its like these days, but back then a
               | _ton_ of those sorts of methods would cause extra
               | allocations (and thus unnecessary GC). That is the very
               | last thing you want in a game engine.
        
               | fein wrote:
               | You are correct. Everything that isn't a native for loop
               | (forEach, map, reduce, etc) is slower than a native for
               | loop.
               | 
               | https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-
               | for_...
        
               | dahart wrote:
               | Looks like it's gotten better recently with ratios like
               | 1.5x - 3x; it wasn't that long ago that using the
               | functional iterators was 10x slower than imperative
               | loops. Still, I have a hard time choosing the functional
               | iterators even the cases that are only 50% slower, and
               | even though I prefer them for how clean and elegant it
               | makes the code. Performance and energy use matters,
               | especially in a physics engine. Defaulting to the slower
               | style might not be visible initially, but is sapping
               | cycles from every corner of the code.
        
             | pharmakom wrote:
             | forEach mixes statements and expressions so (imho) is poor
             | style.
        
         | scaglio wrote:
         | > IBM is probably the last place I expect to find a game dev
         | tutorial
         | 
         | Exactly my thought. Totally unexpected.
        
       | onion2k wrote:
       | A rather more modern physics engine for JS games can be found at
       | https://rapier.rs/. It's written in Rust, compiled to WASM, works
       | for 2D and 3D, and it's _fast_ (well, fast for JS anyway).
        
         | pwdisswordfish0 wrote:
         | Rust isn't JS...
        
           | samkon wrote:
           | Compiled to wasm, it can be used in javascript games.
        
           | onion2k wrote:
           | Through the magic of WASM compilers every language is JS now.
           | 
           |  _has nightmare_
        
             | TheRealPomax wrote:
             | No, now it's web assembly[1], which is a flavour of
             | assembly code that can run in all modern browsers because
             | those browsers add WASM runtimes. It is as far away from JS
             | as you can get while running in a browser. Even Flash and
             | Java were closer to JS than WASM is.
             | 
             | You can implement a WASM runtime _in_ JavaScript (and
             | people have done this, and it turned out to run so well
             | that in some cases the performance hit was basically
             | irrelevant), but that's because JS is Turing complete and
             | any Turing complete system can emulate any other Turing
             | complete system.
             | 
             | [1] https://webassembly.org/
        
             | pwdisswordfish0 wrote:
             | No, that's still not JS. JS is a programming language. It
             | doesn't mean "any program that runs in the browser".
        
               | onion2k wrote:
               | Evidently the " _has nightmare_ " line wasn't enough of a
               | clue that I was making a hilarious joke.
        
       | nileshtrivedi wrote:
       | With the right algebra (PGA2D which adds an additional dimension
       | whose unit vector squares to 0), rigid body physics simulation
       | with collision detection/response can be implemented in < 50
       | lines of Javascript: https://bivector.net/PGADYN.html
       | 
       | Basically in PGA2D, rotations, angular velocity/acceleration,
       | torque etc automatically get handled by geometric product of
       | multivectors. The additional dimension makes all rotations
       | centered at origin, which makes them compose much more nicely.
        
         | cyber_kinetist wrote:
         | I previous had some exposure to rigid body dynamics using the
         | more conventional Lie group notation used in robotics (as seen
         | here:
         | http://hades.mech.northwestern.edu/index.php/Modern_Robotics
         | and
         | https://www.cs.cmu.edu/~junggon/tools/liegroupdynamics.pdf).
         | But I felt the Lie group theory surrounding it were hard to
         | understand (I don't have that much exposure to abstract
         | algebra, I wasn't a mathematics major).
         | 
         | So you think would PGA aid in understanding the weird
         | properties of SO(3) and SE(3) (and its tangent spaces), as well
         | as writing simulation code with it? I know that people use
         | various representations for rigid transformations (screws vs.
         | dual quaternions vs. exponential maps vs. motors), but I am
         | interested which method would work the best in both a
         | theoretical sense (in understanding the kinematics and dynamics
         | more abstractly) and in a pragmatic sense (difficulty of
         | writing and reading actual simulation code, amount of
         | operations used, SIMD-friendliness, etc.)
        
           | nileshtrivedi wrote:
           | I'm not qualified enough to answer your question. What I
           | understand is that PGA is not the only game in town. This
           | framework lets one handle algebra with any number of
           | positive, negative and zero dimensions.
           | 
           | You might find Professor Lasenby's 2020 talk (among others at
           | Bivector Youtube channel) useful:
           | https://www.youtube.com/watch?v=m7v2IUJtC3g
           | 
           | https://www.youtube.com/user/EnkiOrigami/videos
        
         | joshspankit wrote:
         | That website has one of the most elegant simple "wow" moments
         | I've ever seen.
         | 
         | I didn't even notice at first. I just thought "oh that's cool:
         | they've primed the physics so it bounces through neat patterns
         | before settling". But my brain was gently tapping my
         | shoulder... When I listened to it I noticed it was a hypercube,
         | saw " _n_ -dimensional", and WOW
        
         | cancandan wrote:
         | This is great, thanks for the link.
        
       | aby7 wrote:
       | Published November 19, 2012
        
       ___________________________________________________________________
       (page generated 2022-08-24 23:02 UTC)