Gravity

Description

All physics enabled sprites can be affected by a global gravity property. This property can be used to define whether sprites get pulled to the ground quickly, pulled upwards or even to the side.

The example creates five dynamic sprites that are placed alongside each other. The global gravitational force is then set to 10 on the X axis and 10 on the Y axis. This has the effect of pulling all our sprites to the right of the screen and downwards.

Overview

The process involved is as follows:

Creating the sprites

One image is loaded, which is used by five sprites that are all laid out alongside each other:

LoadImage ( 1, "small_silver.png" )

CreateSprite ( 1, 1 ) CreateSprite ( 2, 1 ) CreateSprite ( 3, 1 ) CreateSprite ( 4, 1 ) CreateSprite ( 5, 1 )
SetSpritePosition ( 1, 0, 0 ) SetSpritePosition ( 2, 50, 0 ) SetSpritePosition ( 3, 100, 0 ) SetSpritePosition ( 4, 150, 0 ) SetSpritePosition ( 5, 200, 0 )

Switching physics on

All five sprites have physics enabled:

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

Gravity

Gravity is applied with the function SetPhysicsGravity. This function takes two parameters. The first parameter controls the gravitational force on the X axis, while the second parameter deals with gravity on the Y axis. Whatever values are set here get applied to all your physics enabled sprites. In this example gravity is set to 10 on the X and Y axis:

SetPhysicsGravity ( 10, 10 )

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 code listing carries out the tasks mentioned above as well as providing a background image:

SetVirtualResolution ( 320, 480 )

CreateSprite ( LoadImage ( "background4.jpg" ) )
LoadImage ( 1, "small_silver.png" )
CreateSprite ( 1, 1 ) CreateSprite ( 2, 1 ) CreateSprite ( 3, 1 ) CreateSprite ( 4, 1 ) CreateSprite ( 5, 1 )
SetSpritePosition ( 1, 0, 0 ) SetSpritePosition ( 2, 50, 0 ) SetSpritePosition ( 3, 100, 0 ) SetSpritePosition ( 4, 150, 0 ) SetSpritePosition ( 5, 200, 0 )
SetSpritePhysicsOn ( 1, 2 ) SetSpritePhysicsOn ( 2, 2 ) SetSpritePhysicsOn ( 3, 2 ) SetSpritePhysicsOn ( 4, 2 ) SetSpritePhysicsOn ( 5, 2 )
SetPhysicsGravity ( 10, 10 )
do Sync ( ) loop

Conclusion

Being able to set the gravity for your sprites allows you to create some interesting effects. Try experimenting with the gravity values and see the results.