Quantcast
Channel: User HoldOffHunger - Stack Overflow
Viewing all articles
Browse latest Browse all 55

Answer by HoldOffHunger for How to create a gravity effect with Javascript?

$
0
0

One other framework to consider: Matter.js —Demo: Easy Physics Sandbox in JavaScript.

The Physics

Gravity is hard. That's because gravity is curved spacetime, and we can only make 2d representations of this warping that happens in the third dimension.

On the other hand -- moving an element at a consistent 9.8 m/s^2 in a linear direction towards one direction, that's actually not too hard to implement.

The CSS Solution

All we really need is transition: all 1s linear; to control the speed of the animation, margin-top to animate the element moving downward, and transition-timing-function with a cubic-bezier that's fairly representative of 9.8 m/s^2.

The Demo

document.addEventListener('DOMContentLoaded', function(event) {    document.getElementById('drop').addEventListener('click', function(ev) {        div = document.createElement('div');        div.classList.add('gravity-affected-object');        image = document.createElement('img');        image.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Red_Apple.jpg/640px-Red_Apple.jpg';        image.width = 100;        image.classList.add('gravity-affected-object');        div.style.position = 'absolute';        div.style.left = '50%';        div.appendChild(image);        document.getElementById('page-top').appendChild(div);        setTimeout(function() {            div.style.marginTop = '1000px';        }, 100);    });});
.gravity-affected-object {    transition: all 1s linear;    transition-timing-function: cubic-bezier(0.33333, 0, 0.66667, 0.33333);    z-index: -5000;}
<div id="page-top"></div><button id="drop">Drop</button>

Viewing all articles
Browse latest Browse all 55

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>