Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a gravity effect with Javascript?

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?

like image 465
Towhid Avatar asked Jan 11 '12 19:01

Towhid


2 Answers

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.

like image 121
nwellcome Avatar answered Oct 11 '22 19:10

nwellcome


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

like image 29
benahm Avatar answered Oct 11 '22 20:10

benahm