How to create a gravity effect with Javascript?

Towhid picture Towhid · Jan 11, 2012 · Viewed 22.2k times · Source

Google gravity and gravity script are two nice demonstrations. but no source code or tutorials are available. and the original JS files are very big. How can I create a Gravity effect with Drag & drop(specially being "Throw able" and "rotatable" like google gravity) on a certain element?

Answer

nwellcome picture nwellcome · Jan 12, 2012

You will want to start with a physics engine, the one Google Gravity uses is Box2Djs which is a javascript port of Box2D. You can read the manual for Box2D to learn how to use it, though the manual itself states that you will have little idea what you are doing without some knowledge of rigid body physics (force, impulse, torque, etc), though these examples may help you get started.

If you want to write the physics engine yourself you will have to at least implement 2D rigid body dynamics and collision detection for it to look like the examples you gave. A tutorial for doing that would be called a computer simulation class and would have a linear algebra and physics I prerequisite, it's not a trivial task.

Afterwards, you will have to learn about javascript animation techniques. I recommend learning about window.requestAnimationFrame. Using setInterval(stepFunction, time) will work but it won't be as efficient as it could be in modern browsers.