Moving sprites using the virtual resolution

Description

In this example we're going to place a sprite on screen and move it using the approach of a virtual resolution.

Overview

The process involved is as follows:

Virtual Resolution

We begin by setting our virtual resolution to dimensions of 320 x 480:

SetVirtualResolution ( 320, 480 )

Load an image

Now we can load an image for our sprite:

image = LoadImage ( "blue.png" )

This line calls LoadImage passing in the filename "blue.png", it then returns an ID number which gets saved in the variable image. This ID number is now treated as a handle to our image and can be used later on when referring to it.

Creating a sprite

Now that we have an image loaded into memory we're ready to create a sprite and attach this image to it. This is achieved by calling the command CreateSprite.

sprite = CreateSprite ( image )

Here we call CreateSprite passing in an ID number for our image and returning an ID number for the sprite. We're effectively saying create a sprite, attach this image to it and give us back an ID number for this sprite. This ID number for the sprite can be stored for use later on when dealing with sprite properties, for example.

Main Loop

Up to this point we have set a virtual resolution, loaded an image and created a sprite that uses this image. We're nearly ready to run our application and see the results. Prior to this we need to ensure one more thing - in our main loop we must call Sync to ensure the screen gets updated and its contents drawn. The command Sync takes no parameters and can be called in your main loop like this:

do
    Sync ( )
loop

Move our sprite in the main loop

To move our sprite around the screen we call the function SetSpritePosition. This function takes three parameters - the ID number of the sprite, new X position on screen and the new Y position on screen. As we're using a virtual resolution the X and Y positions refer to screen coordinates. If we were using the percentage based system these coordinates would be percentages. For our purposes we want to move our sprite from its initial position (which will be 0, 0 by default) and over towards the right hand side of the screen. This is achieved by setting a variable to 0, incrementing it slowly each frame and then passing it into SetSpritePosition, as shown in this code:

SetSpritePosition ( sprite, x#, 0 )

x# = x# + 0.5

Full code listing

Everything is now in place. Here's the final code for our program:

SetVirtualResolution ( 320, 480 )

CreateSprite ( LoadImage ( "background1.jpg" ) )
image = LoadImage ( "blue.png" )
sprite = CreateSprite ( image )
do SetSpritePosition ( sprite, x#, 0 )
x# = x# + 0.5
Sync ( ) loop

Conclusion

We're now all set to run our application and see the results on screen.