Tutorial - Physical World And Bodies

With Sprite Basic, you can create sprites and make them moving through code input. However, if you want objects having their own behaviours and move under forces, you might want to create a physical world and add bodies to it.
Bodies are just like sprites, except that you can apply behaviors and forces to them, that will rule the way they move and interact between each other and detect their collisions
We will now create a physical world and add some bodies to it

Setting up the world

In OnInit() method, we start by defining logical screen dimensions as seen in the Web GL Renderer tutorial
Then we create the world and the renderer, and add the renderer to the world
That's it ! You're now ready to add behaviours then bodies to your world

width=app.getLogicalWidth() app.setLogicalWidth(width) height=app.getLogicalHeight() world=app.createWorld() // create a physical world renderer=app.createRenderer() world.addRenderer(renderer) // set the world renderer

Adding standard behaviours to the world

First we defines the bounds of the world within which we want the bodies to be constrained. Without this, bodies would go out of screen
We choose here to set world dimensions same as screen dimensions, but you could set the bounds to only part of the screen
This however is not enough, we need to add behaviour 'body-impulse-response', so bodies actually bounce off the bounds. We also add a 'constant-acceleration' behavior that is by default set to gravity. However you can add optional x-axis and y-axis values for this behaviour (please refer to documentation for more info)

world.setBounds(0, 0, width, height) // limits screen bounds so bodies collide on edges of screen world.addBehavior("body-impulse-response") // add behavior for bouncing over collision world.addBehavior("constant-acceleration") // add gravity constantaly to all bodies objects

Adding Bodies

Now we will add some bodies to the world. We could add bodies made of textures through createBody() function, but we will use here a very convenient function for demos and game prototyping
Function createShapedBody() create a body by specifying a circle, rectangle, roundRectangle or ellipse shape, with dimensions and graphical style
We could have add optional vx and vy parameters to define original speed, as well as the layer to draw on, just as a sprite
We set a bounce factor randomly, and you can see in the demo that circle bodies, move down under the force of attraction and bounce off the ground more or less, until complete stop

for i=1 to count object ball = world.createShapedBody("circle", "ball", "dynamic", 0xffffff, 0xff0000, 3, rnd(width), rnd(height), 32, 32) // red circle with a white border of 3 px, radius 32/2=16px and placed randomly ball.setBounciness(0.75+rnd(0.25)) // set bounce at random value next

You can try the code in TUTO-PHYSIC-WORLD project on the Guest Account
You can find reference of the functions used in the Documentation