Display Sub-Images with Code in GameMaker: Studio
The following example of randomly displaying sub-images is based on GameMaker: Studio’s in-software tutorial on coding a breakout game. Get started with coding in a very simple way — by using only two lines of code that can really change how your game looks.
Create a Sprite with several sub-images (for example, each sub-image could be a different colored brick).
The Sprite should appear in the Resource tree.
Choose Resources→Create Object.
The Object Properties window appears.
In the Name field, type something like obj_brick (see the figure).The Object Properties window for the brick Object.
From the Sprite drop-down list, select the Sprite with the sub-images that you just created.
A thumbnail of the image appears in the Sprite section, and the name of the image appears in the field (refer to the figure).
Choose Add Event→Create.
A Create Event appears in the Events section of the Object Properties window (refer to this figure).
Drag and drop the Execute Code Action from the Control tab into the Actions section.
An empty code window appears with its own menu.
In the code window (shown in this figure), type the following code:GameMaker: Studio’s code window.
image_speed = 0; image_index = floor(random(image_number));
Click the green check mark in the icon menu.
The code window is saved and closed.
Click OK in the Object Properties window.
The Object Properties are saved and closed.
Place an Instance of the Object in the Room.
From the main menu, choose Run→Run Normally, to test the game.
The compile window displays the compilation of the game. When the game starts, you should see randomly sorted bricks, as shown here.Randomly sorted bricks.
This code sets the speed of the image to 0. This is the speed GameMaker uses to show the individual sub-images of the Sprite. The default is 1, which means that normally GameMaker displays a single frame (one of the sub-images) in each step of the game.
By using 0 as the image speed, you’re telling GameMaker not to animate the Sprite and to show only a single sub-image. The second line of the code randomly selects one of the sub-images that will be displayed during the game.
If you were to use 0.5 as the speed, then the sub-images would appear in slow motion or at half the speed. If you want the sub-images to appear very quickly, you could enter a value of 2.
You may have noticed that the code window is color-coded — that is, certain text appears in different colors than others. That is a useful feature of GameMaker, in that comments, functions, variables, and so on are highlighted in different colors.
If you don’t like the color coding, or you want to use your own custom colors, you can update the Preferences — from the main menu choose, File→Preferences, and then select the Scripts and Code tab as shown in this figure.