Thursday 5 April 2012

Images and Sprites

In order to use a graphic such as the one provided in the previous post, we need to do two things;
  • Load the graphic file
  • Map the Image onto a screen object  - called a sprite
In both cases, a reference number is used to identify the object in subsequent commands.  

AGK is flexible when it comes to references, you can specify one when the object is loaded or created or you can let it choose one and tell you what it is.   I prefer the second option as I find it too easy to make mistakes when I have to unique pick numbers.

Images are loaded using the LoadImage() command, with the name of the file inside the brackets.  If you put a reference in the brackets as well, AGK will use this, otherwise it will return a reference  which needs to be stored in a variable.

Sprites are created using the CreateSprite() command, in this case the value in brackets is the reference of the image that you want the sprite to look like.

Sprites are then positioned using the SetSpritePosition() command which uses the sprite reference and an X and Y Coordinate for where you want it.

To see this in action, add the following commands to the very start of the project;

imageRef = loadImage( "finger.png" )
spriteRef = createSprite( imageRef )
setSpritePosition( spriteRef , 10 , 10 )

In the first line, the variable imageRef is used to store the reference assigned by AGK to the image loaded from the file finger.png.

In the second line, the variable spriteRef is used to store the reference assigned by AGK to the sprite created using the image reference stored in imageRef.

In the third line , the sprite indicated by the reference stored in spriteRef is moved so that it's top left corner is at X position 10 and y position 10.

This is what the project should look like now in the editor
Notice that the editor shows you that unsaved changes have been made in several ways;
  • In the Project tree, main.agc shows a ! character
  • Above the edit window, the main.agc tab starts with a * character
  • In the edit window, changed lines have a yellow strip in the margin
Also notice the various colours used show what each word represents;
  • variables are black
  • commands are blue
  • text strings are red
  • values are green
This helps you keep track of what is what.

Compile the project and the ! in the Project tree and the * in the tab title should disappear, indicating that the project has been saved.  The yellow strip will also turn green which indicates that these changes have been saved.
The green strip indicates that the changes can reverted back with undo.

Run the project and the output window should look like this 
If not, go back and check the spelling in each of the lines and make sure the image file has the correct name.

No comments:

Post a Comment