- Box2D for Flash Games
- Emanuele Feronato
- 455字
- 2021-08-05 18:44:25
Defining the Box2D World
Like all worlds, the Box2D World has a gravity , so the first thing you need to do is define world gravity.
- In your
Main
function, add the following line:var gravity:b2Vec2=new b2Vec2(0,9.81);
This introduces our first Box2D data type:
b2Vec2
.b2Vec2
is a 2D column vector that is a data type, which will store x and y components of a vector. As you can see, the constructor has two arguments, both numbers, representing the x and y components. This way we are defining thegravity
variable as a vector withx=0
(which means no horizontal gravity) andy=-9.81
(which approximates Earth gravity).Physics says the speed of an object falling freely near the Earth's surface increases by about 9.81 meters per second squared, which might be thought of as "meters per second, per second". So assuming there isn't any air resistance, we are about to simulate a real-world environment. Explaining the whole theory of a falling body is beyond the scope of this book, but you can get more information by searching for "equations for a falling body" on Google or Wikipedia.
- You can set your game on the move with the following line:
var gravity:b2Vec2=new b2Vec2(0,1.63);
You can also simulate a no gravity environment with the arguments set at
(0,0)
:var gravity:b2Vec2=new b2Vec2(0,0);
- We also need to tell if bodies inside the world are allowed to sleep when they come to rest, that is when they aren't affected by forces. A sleeping body does not require simulation, it just rests in its position as its presence does not affect anything in the world, allowing Box2D to ignore it, and thus speeding up the processing time and letting us achieve a better performance. So I always recommend to put bodies to sleep when possible.
- Add the following line, which is just a simple Boolean variable definition:
var sleep:Boolean=true;
- And finally, we are ready to create our first world:
var world:b2World = new b2World(gravity,sleep);
- Now we have a container to manage all the bodies and perform our dynamic simulation.
- Time to make a small recap. At the moment, your code should look like the following:
package { import flash.display.Sprite; import Box2D.Dynamics.*; import Box2D.Collision.*; import Box2D.Collision.Shapes.*; import Box2D.Common.Math.*; public class Main extends Sprite { public function Main() { var gravity:b2Vec2=new b2Vec2(0,9.81); var sleep:Boolean=true; var world:b2World = new b2World(gravity,sleep); } } }
Now you learned how to create and configure a Box2D World. Let's see how can you simulate physics in it.
- Spark快速大數據分析(第2版)
- Python數據分析、挖掘與可視化從入門到精通
- Live Longer with AI
- 數據驅動設計:A/B測試提升用戶體驗
- 數據庫原理與應用(Oracle版)
- Python數據分析與挖掘實戰(第3版)
- 科研統計思維與方法:SPSS實戰
- SQL Server 2012實施與管理實戰指南
- R Machine Learning Essentials
- Python 3爬蟲、數據清洗與可視化實戰
- SQL Server 2008寶典(第2版)
- 數據中臺實戰:手把手教你搭建數據中臺
- Machine Learning for Mobile
- Redis 6開發與實戰
- Learning Construct 2