How to create a gravity effect with Javascript?

23,642

Solution 1

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.

Solution 2

Look a this jquery plugin on github JQuery.throwable just do $("Selector").throwable() and the object will be under gravity

Share:
23,642
Towhid
Author by

Towhid

Updated on July 09, 2022

Comments

  • Towhid
    Towhid almost 2 years

    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?

  • Towhid
    Towhid over 12 years
    thanks,JS version of it is available @ box2d-js.sourceforge.net/index2.html . but I want to create this effect on actual HTML elements. for example I have a few Social buttons which fall when page is activated and users can throw them and play with theme:) . Box2dJS is great for Web based game developing but I think its based on "convas" not HTML elements.