Getting started with physics

Description

The physics command set within AGK provides a 2D rigid body simulation library for games. It can be used to make sprites move in believable ways and make games more interactive. In this example we explore the basics of getting started with physics by creating 5 sprites, positioning them in a row, turning physics on and seeing the results.

Overview

The process involved is as follows:

Creating 5 sprites

One image is loaded (a football), which is then used by 5 sprites and these sprites are all laid out alongside each other:

LoadImage ( 1, "small_ball.png" )

CreateSprite ( 1, 1 ) CreateSprite ( 2, 1 ) CreateSprite ( 3, 1 ) CreateSprite ( 4, 1 ) CreateSprite ( 5, 1 )
SetSpritePosition ( 1, 0, 0 ) SetSpritePosition ( 2, 60, 0 ) SetSpritePosition ( 3, 120, 0 ) SetSpritePosition ( 4, 180, 0 ) SetSpritePosition ( 5, 240, 0 )

Switching physics on

As it stands now our sprites will be drawn on screen and only move based on our control of them. When switching physics on the underlying simulation code will take over and be responsible for providing a realistic simulation. Enabling physics for sprites is handled with a call to the function SetSpritePhysicsOn. By default sprites are not tied into the physics simulation The function SetSpritePhysicsOn takes two parameters - the first is the ID number of the sprite and the second is the type of physics objects, with suitable values being 1 for a static object, 2 for a dynamic object and 3 for a kinematic object. This demo is going to examine what happens when we switch all of our sprites to dynamic objects. This is handled with the following code:

SetSpritePhysicsOn ( 1, 2 )
SetSpritePhysicsOn ( 2, 2 )
SetSpritePhysicsOn ( 3, 2 )
SetSpritePhysicsOn ( 4, 2 )
SetSpritePhysicsOn ( 5, 2 )

Main loop

The main loop in this example does not take any action. All it needs to do is make a call to Sync to ensure the screen is updated.

do
   Sync ( )
loop

Full code listing

The final program only has one alteration and that is the addition of a background sprite. Here's the final code:

SetVirtualResolution ( 320, 480 )

CreateSprite ( LoadImage ( "background3.jpg" ) )
LoadImage ( 1, "small_ball.png" )
CreateSprite ( 1, 1 ) CreateSprite ( 2, 1 ) CreateSprite ( 3, 1 ) CreateSprite ( 4, 1 ) CreateSprite ( 5, 1 )
SetSpritePosition ( 1, 0, 0 ) SetSpritePosition ( 2, 60, 0 ) SetSpritePosition ( 3, 120, 0 ) SetSpritePosition ( 4, 180, 0 ) SetSpritePosition ( 5, 240, 0 )
SetSpritePhysicsOn ( 1, 2 ) SetSpritePhysicsOn ( 2, 2 ) SetSpritePhysicsOn ( 3, 2 ) SetSpritePhysicsOn ( 4, 2 ) SetSpritePhysicsOn ( 5, 2 )
do Sync ( ) loop

Conclusion

Try experimenting with switching physics on or off for sprites and see the impact it makes. Notice how physics enabled sprites are affected by forces such as gravity, which will result in them falling to the bottom of the screen.