如何用Javascript创建重力效果?
Google 重力和重力script 是两个很好的演示。 但没有可用的源代码或教程。而且原来的JS文件很大。 如何使用 Drag & 创建重力效果在某个元素上放置(特别是“可投掷”和“可旋转”,如谷歌重力)?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要从物理引擎开始,Google Gravity 使用的引擎是 Box2Djs,它是一个 javascript 端口Box2D。您可以阅读 Box2D 的手册来学习如何使用它,尽管手册本身指出,如果没有一些刚体物理知识(力、脉冲、扭矩等),您将几乎不知道自己在做什么,尽管这些示例可能帮助您开始。
如果您想自己编写物理引擎,您至少必须实现 2D 刚体动力学和碰撞检测,使其看起来像您给出的示例。这样做的教程将被称为计算机模拟课程,并且有线性代数和物理学的先决条件,这不是一项简单的任务。
之后,您将必须学习 javascript 动画技术。我建议学习
window.requestAnimationFrame
。使用setInterval(stepFunction, time)
可以,但它不会像在现代浏览器中那样高效。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
. UsingsetInterval(stepFunction, time)
will work but it won't be as efficient as it could be in modern browsers.在 github 上查看这个 jquery 插件 JQuery.throwable
只需执行
$("Selector"). throwable()
,物体就会受到重力作用Look a this jquery plugin on github JQuery.throwable
just do
$("Selector").throwable()
and the object will be under gravity另一种值得考虑的框架:Matter.js — 演示:JavaScript 中的简单物理沙箱 。
物理
重力很难。这是因为引力是弯曲的时空,我们只能对三维中发生的这种扭曲进行二维表示。
另一方面,以一致的 9.8 m/s^2 的速度沿线性方向向一个方向移动一个元素,这实际上并不难实现。
CSS 解决方案
我们真正需要的是
transition: all 1s Linear;
来控制动画的速度,margin-top
来动画元素向下移动,以及具有相当具有代表性的 9.8 m/s^2 的
。cubic-bezier
的过渡计时函数演示
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, andtransition-timing-function
with acubic-bezier
that's fairly representative of 9.8 m/s^2.The Demo