TweetFollow Us on Twitter

REALbasic Sprites Volume Number: 16 (2000)
Issue Number: 8
Column Tag: Programming

REALbasic Sprites

By Erick J. Tejkowski

Develop powerful games in minutes


Game programming has long been a tradition of highly specialized source code, libraries, and programming trickery, strictly for übergeeks. Until now. Armed with a copy of REALbasic and this article, you will be writing your own games in no time at all.

For high-speed games, it is customary for programmers to use special code to draw at high speeds (often referred to as "blitting" routines). This stems from the fact that the native drawing routines available in the Mac Toolbox are too slow for fast drawing, such as that required by animation. Beginners will be glad to learn that REALbasic has these abilities built in. With only a few lines of code, a programmer can attain high-speed sprite-based animation. Add a few more lines of code and you have a game. REALbasic takes care of all the nasty drawing routines behind the scenes and lets us focus on the elements of the game. This article will demonstrate animation and game creation using REALbasic sprites. By the end of the article, you should be able to complete a small arcade-style game.

Building the Sprites

Begin the game project by opening your favorite resource editor. For our purposes, the free ResEdit from Apple will do just fine. Create a new file and name it "Resources". This is the only name REALbasic understands for resource files added directly to projects in the IDE, so be sure to spell it correctly. In this new resource file, create three resources of type 'cicn' and change the ID# to 1280, 1290, and 1300 respectively by selecting the Resource:Get Resource Info menu. In cicn #1280, create a graphic for the hero of our game. In cicn #1290, draw an adversary. Finally, cicn #1300 contains a picture of a projectile. For this example, we will use an airplane theme. By now, you should have something that looks like Figure 1.

Figure 1. The Sprite Graphics.

Now that the sprite graphics have been created, save the Resources file and start REALbasic.

Building the Project

When REALbasic starts, a new project is created automatically. Drag the newly created resource file into the project. Now, open Window1 and drag a StaticText , a PushButton , and a SpriteSurface control onto the window. The StaticText will display the results of the game (i.e. win or lose), the PushButton will start the game, and the SpriteSurface will control all of the animation and game play. Figure 2 shows the completed interface.

Figure 2. The Completed Window1 Interface.

Once the interface has been built, double click Window1 to open the Code Editor. With the Code Editor opened, create the Properties in Listing 1 by selecting New Property from the Edit menu.

Listing 1. Window1 Properties.

BadguySprite(10) as Sprite
GoodGuySprite as Sprite
GunSprite as Sprite	
gunvisible as Boolean
NumOfBadGuys as Integer
leftEdge as Integer
topEdge as Integer

Sprite properties are pictures that can be controlled by a SpriteSurface. We will need 10 sprites representing the attacking enemies, one representing the hero, and one used for the gunfire that the hero can shoot. The Boolean variable gunvisible will allow us to turn the gunfire on and off. The integer NumOfBadGuys , as one might expect, will keep track of the number of BadguySprites remaining. The final two integer variables (leftEdge and topEdge) will be used to center the SpriteSurface on the screen.

In addition to these properties, create three methods named InitSprites, ClearAllSprites, and RemakeGun by selecting New Method from the Edit menu. The InitSprites method will initialize all of the sprites defined in Listing 1. Open the Code Editor to the InitSprites method and enter the code from Listing 2.

Listing 2. The InitSprites Method.

Sub InitSprites()
dim p as picture
dim i as integer

//init the good guy

//init the gunfire

//init the bad guys
for i=1 to 10

End Sub

The InitSprites method demonstrates how each of the Sprites is created. First, the icons created earlier are opened into a Picture object. Next, the NewSprite method of SpriteSurface1 is called, passing the Picture, and Width and Height of the Picture as parameters. Once the Sprite has been created, its X and Y positions are initialized. The SpriteSurface will measure 640x480, so the GoodGuySprite will begin life somewhere near the bottom middle of the screen. The gunfire starts off as not being visible (i.e. gunvisible=false), so we assign its X postion somewhere off the screen (GunSprite.x=-200). Later, when we want it visible to the user, we will simply move it to a positive X position. The ten BadguySprites will begin at random X positions and Y positions somewhere between -250 and -50, making them initially invisible. This will change later, however, when they move down the screen towards the GoodyguySprite. The last thing to notice here is the Group property of each of the Sprites. The Group number is used for detecting collisions. Sprites with the same Group number will not collide with each other. Sprites with different Group numbers produce collisions. Now, when we talk about producing collisions, what this really means is that the Collision Event of the SpriteSurface will be fired. For now, it is sufficient to know that the GunSprite and the BadGuys have different Group numbers so that they may collide. Further, the BadGuySprites have a Group number that is different from the GoodguySprite, allowing them to collide.

Since all good things must come to an end, we need to include some code to destroy everything we have created. Open the Code Editor, navigate to the ClearAllSprites method, and enter the code in Listing 3. During the execution of the game, we may need to kill a sprite (e.g. when GunSprite and badguySprite collide). Therefore, we should not assume that all sprites will always be around. This is the reason we check for nil status of a sprite before trying to kill it. If we try to kill a non-existent sprite, an error will result causing the application to crash.

Listing 3. The ClearAllSprites Method.

Sub ClearAllSprites()
dim i as integer
//kill the GoodguySprite
if GoodGuySprite<>nil then
end if
//kill the GunSprite
if GunSprite<>nil then
end if
//kill the BadguySprites
for i=1 to 10
if BadguySprite(i)<>nil then
end if
End Sub

One final auxiliary method to code is called RemakeGun. This method will allow us to recreate a GunSprite in the middle of game play. Although we already created one in the InitSprites method, it might be destroyed during game play when it collides with a BadguySprite. Open the Code Editor window, navigate to the RemakeGun method, and enter the code in Listing 4.

Listing 4. The RemakeGun Method.

Sub RemakeGun()
dim p as picture
//reinitialize the gunfire
End Sub

With the window's properties and methods defined, it is time to add functionality to the various controls. To begin, fill the screen with Window1 by adding code into its Open event. This is really only cosmetic in nature. The SpriteSurface will later take over the whole screen anyway. This is what the player will see before the game begins and in between rounds.

Sub Open()
End Sub

To get the game started, enter the code in Listing 5 into the Action Event of PushButton1.

Listing 5. The Action Event of PushButton1.

Sub Action
End Sub

If any sprites are still around from previous games, they are cleared by the ClearAllSprites method. Next all of the sprites are initialized with InitSprites and the game play begins by calling the Run method of SpriteSurface1.

The SpriteSurface

At the heart of REALbasic sprite animation is the SpriteSurface control. It is a bit of an unusual control in that it has a dual personality. It acts like a Canvas control drawing graphics in a similar fashion, while periodically executing code like a Timer. The FrameSpeed property of the SpriteSurface is the rate at which the timed functions of a SpriteSurface fire. To calculate the FrameSpeed, divide 60 by the desired frames per second and round up to an integer. For example, to achieve a speed 30 frames per second:

60 / 30 = 2 (the FrameSpeed)

A FrameSpeed of 0 (zero) is the fastest speed at which a SpriteSurface can draw. A setting of 1 or 2 is typical, depending on speed and complexity required. The Run method of SpriteSurface1 was called earlier in the PushButton1 Action event. This causes the SpriteSurface to periodically fire the NextFrame event at the FrameSpeed rate until the SpriteSurface1.close method is called. As the NextFrame event fires, we look at the current conditions of all of the sprites and change them if necessary. For example, it is in the NextFrame event where we check for keys being pressed. If a key is pressed, then some aspect of a sprite can be changed (e.g. position). REALbasic takes care of doing all the redrawing for us. We simply tell it where to draw.

Listing 5 shows the NextFrame event of SpriteSurface1. In it, you will notice some other things going on. First off, a scoreboard is drawn. The scoreboard is simply a string that displays the number of BadguySprites remaining. Behind this string is a small blue rectangle, which serves the purpose of erasing the number each time. The color blue is used, because it will also be the color of the entire background of the SpriteSurface. After redrawing the scoreboard, the code checks the keyboard for keys being pressed. It looks at the left, right, up, and down arrow keys, as well as the space bar. If any of them are depressed, appropriate actions are taken. One piece of code specific to the GunSprite here is ShootingSound is a sound file that has been dragged into the project window. Be sure to make your sounds relatively short, because long sounds can impede smooth animation. Finally the BadGuySprites are moved.

Listing 5. The SpriteSurface1 NextFrame event.

Sub NextFrame()
dim i as integer
//draw the scoreboard,0,100) 150+leftEdge,467+topEdge,40,13,255,255)"Geneva"
// ! put the following code all on one line ! "Bad Guys Remaining: " + str(NumOfBadGuys), 50+leftEdge,477+topEdge

if me.keyTest(123) then //check left arrow key 
//plane moves left
if GoodGuySprite.x<=0 then
end if
end if
if me.keyTest(124) then //check right arrow key 
//plane moves right
if GoodGuySprite.x>600 then
end if
end if
if me.keyTest(126) then //check up arrow key 
//plane moves up 
if GoodGuySprite.y<350 then
end if
end if
if me.keyTest(125) then //check down arrow key 
//plane moves down
if GoodGuySprite.y>435 then
end if
end if

if me.keyTest(49) then //fire=spacebar
//shoot the gun
if gunvisible=false then
//init the gunfire position here
end if
end if

//now check the position of gun only if it's turned on
if gunvisible=true then
//if the gun has reached the top of the screen
//hide it again and turn it off
if GunSprite.y<0 then
end if
end if
//advance the badguys  
for i=1 to 10
//this is the speed of descent (increase for faster movement)
//if we have reached the bottom of the screen
//go back up to the top at some random x position
if BadguySprite(i).y>447 then
end if

End Sub

So far, this code will produce a nice animation where the GoodguySprite can navigate and shoot at the approaching BadguySprites.

SpriteSurface Collisions

When a GunSprite hits a BadguySprite, nothing happens yet. Nor will anything occur if the BadguySprite manages to run into the GoodguySprite. This is the function of the SpriteSurface1 Collision Event. Listing 6 details the code for the SpriteSurface's Collision Event. This is where the Sprite Group numbers from earlier in this article become important. The Collision Event of a SpriteSurface is automatically passed the Group numbers of the sprites that have collided. In the event, we simply check to see which two sprites have collided and then take some action. In this example, we will only look at two types of collisions - both the GunSprite and BadguySprite have collided or the GoodguySprite and BadguySprite have collided. If the GunSprite has collided with a BadguySprite, then we close both of the sprites (in effect "killing" them), play a sound, decrease the number of NumOfBadGuys variable, and call RemakeGun for the next time a user fires the gun. We must also check to see if all of the BadguySprites have been killed. If so, then the game is over and the player has won. Finally, if a BadguySprite has managed to collide with the GoodguySprite then the game is over and the player has lost.

Listing 6. The Collision Event of SpriteSurface1.

Sub Collision (s1 as Sprite, s2 as Sprite)
//GunSprite and BadguySprite have collided
if and then
RemakeGun // since we killed the gun sprite, init it again
if NumOfBadGuys=0 then
Statictext1.text="You Win!"
end if
end if

//GoodguySprite and BadguySprite have collided
if and then
Statictext1.text="You Lose!"
end if
End Sub

To spice things up a little, it is often desirable to draw a background behind the game. The SpriteSurface background is broken up into a grid of 64x64 squares. The PaintTile event takes care of refreshing these background tiles. To fill the background with a solid blue color, enter this code into the PaintTile event of SpriteSurface1.

Sub PaintTile (g as Graphics, xpos as Integer, ypos as Integer)
g.fillrect 0,0,64,64
End Sub

Keep in mind that any standard graphics drawing can take place in the PaintTile event. The final step is to add some code to the Open event of SpriteSurface1. Like the Window1 Open event code, this code is strictly cosmetic. It has been adopted from code by Matt Neuberg in his book REALbasic: The Definitive Guide. It centers SpriteSurface1 on the screen.

Sub Open()
leftEdge = (Screen(0).width - 640) \ 2
topEdge = (Screen(0).height - 480) \ 2
me.surfaceleft = leftEdge + ((640-me.surfacewidth) \ 2)
End Sub

Having completed the code, it is time to test the finished application. Select Debug:Run menu. Click PushButton1 and play the game. If something goes wrong, recheck your code for accuracy and make sure that you have added all of the necessary auxiliary files (the resource file and the sound files). If all else fails, you can download the finished source code from MacTech's web site.


In this article, we took a brief look at Sprites in REALbasic by constructing a game. The game could be upgraded in a number of ways. Hopefully, this article gives you some basic background about how to make some of these changes yourself. If you would like more information about game development on the Macintosh particularly with regard to REALbasic, be certain to check the Reference section at the end of this article.


Erick Tejkowski is still looking for a decent version of Moon Patrol[TM] for the Mac. You can reach him at


Community Search:
MacTech Search:

Software Updates via MacUpdate

Geekbench 4.1.1 - Measure processor and...
Geekbench provides a comprehensive set of benchmarks engineered to quickly and accurately measure processor and memory performance. Designed to make benchmarks easy to run and easy to understand,... Read more
iMazing 2.3.3 - Complete iOS device mana...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
TeamViewer 12.0.81279 - Establish remote...
TeamViewer gives you remote control of any computer or Mac over the Internet within seconds, or can be used for online meetings. Find out why more than 200 million users trust TeamViewer! Free for... Read more
Safari Technology Preview 11.0 - The new...
Safari Technology Preview contains the most recent additions and improvements to WebKit and the latest advances in Safari web technologies. And once installed, you will receive notifications of... Read more
PDFpen 9.1 - $74.95
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
GraphicConverter 10.4.3 - $39.95
GraphicConverter is an all-purpose image-editing program that can import 200 different graphic-based formats, edit the image, and export it to any of 80 available file formats. The high-end editing... Read more
Fission 2.3.2 - Streamlined audio editor...
Fission can crop and trim audio, paste in or join files, or just rapidly split one long file into many. It's streamlined for fast editing. Plus, it works without the quality loss caused by other... Read more
EarthDesk 7.2 - Striking real-time anima...
EarthDesk replaces your static desktop picture with a rendered image of Earth showing correct sun, moon, and city illumination. With an Internet connection, EarthDesk displays near-real-time global... Read more
Things 3.1.1 - Elegant personal task man...
Things is a task management solution that helps to organize your tasks in an elegant and intuitive way. Things combines powerful features with simplicity through the use of tags and its intelligent... Read more
iDefrag 5.2.0 - Disk defragmentation and...
iDefrag helps defragment and optimize your disk for improved performance. iDefrag Features Supports HFS and HFS+ (Mac OS Extended). Supports case sensitive and journaled filesystems. Supports... Read more

Latest Forum Discussions

See All

Aero Effect (Games)
Aero Effect 1.0.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.1 (iTunes) Description: Race an aerodynamic thingy through a maze of animated, geometric peril and plunge into a mysterious grid of pixels, all while... | Read more »
Linelight (Games)
Linelight 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Linelight is an elegant, minimalist puzzle game set in a universe of lines. Its puzzles will awake your mind as the music flows... | Read more »
Fighting Fantasy Legends (Games)
Fighting Fantasy Legends 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Create your own adventures in a dangerous land of monsters, treasures and traps. From renowned authors Steve Jackson... | Read more »
Knight Fever is a new take on the classi...
Knight Fever lands on the Google Play, and you won’t want to miss it if you’re a devoted RPG fan. Developed by indie creatives Buff Studios, the game looks like a retro RPG with some exciting new twists. | Read more »
Steam Panic (Games)
Steam Panic 1.0 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: Steampunk puzzle in which you spin the playfield to put yourself back together. Dear Reader,Enclosed is a copy of my bizarre 1935... | Read more »
Time Crash (Games)
Time Crash 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Time is about to Crash! It’s up to you to save the city! Time Crash is a 3D first person runner which lets you play as a powerful... | Read more »
Galaxy of Pen & Paper (Games)
Galaxy of Pen & Paper 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: *** NO IN-APP PURCHASES! ****** PREMIUM FOREVER *** THE ULTIMATE ROLE-PLAYING SIMULATION GOES TO SPACE! | Read more »
Niantic reveals more Pokémon GO legendar...
Oof. Pokémon GO Fest Chicago was pretty much a fiasco, huh? Niantic is feeling the heat from fans for their first big event that ultimately ended in failure. So much so that they've released a much longer apology that gives a full run down of... | Read more »
The 5 best life-saving apps for dog owne...
While it's true that dogs are man's best friend, they're also a pretty big responsibility. We want to give our dogs the best lives, but with busy schedules that's not always easy. Luckily, though, there are a bunch of quality apps out there that... | Read more »
Mix and match magical brews in Miracle M...
Miracle Merchant, the charming fantasy card game by Tiny Touch Tales, is arriving next week. The development team, which also brought you Card Crawl and Card Thief, announced the game's launch with a pleasant little trailer that showcases the game'... | Read more »

Price Scanner via

27-inch 3.5GHz iMac on sale for $100 off MSRP...
Adorama has the new 27″ 3.5GHz iMac (MNEA2LL/A) on sale for $1899 including free shipping. Their price is $100 off MSRP. Adorama charges sales tax for purchases in NY & NJ only. Read more
Seven Cities, One Phone: OtterBox Sends iPhon...
Plenty of people have trekked around the world, but what about a globe-trotting iPhone? OtterBox is sending an iPhone around the world to capture the adventures of a diverse set of global ambassadors... Read more
L-Card Pro App May Spell End For Paper Busine...
OrangeTreeApps, LLC has announced the release of L-Card Pro 1.1, an update to their business app for iOS and Android devices that introduces eco-friendly, affordable, electronic business cards on the... Read more
Clearance previous generation iMacs, Apple re...
Apple has previous-generation Certified Refurbished 2015 21″ & 27″ iMacs available starting at $849. Apple’s one-year warranty is standard, and shipping is free. The following models are... Read more
27-inch 3.4GHz iMac on sale for $1699, save $...
MacMall has the new 2017 27″ 3.4GHz iMac (MNE92LL/A) in stock and on sale for $1699 including free shipping. Their price is $100 off MSRP. Read more
Photographer Explains Choosing Dell Laptop Ov...
Last week photographer and video blogger Manny Ortiz posted a video explaining the five most important reasons he settled on a Dell XPS 15 laptop instead of a MacBook Pro for his latest portable... Read more
Sale! 10-inch iPad Pros for $50 off MSRP, no...
B&H Photo has 64GB and 256GB 10.5″ iPad Pros in stock today and on sale for $50 off MSRP. Each iPad includes free shipping, and B&H charges sales tax in NY & NJ only: – 10.5″ 64GB iPad... Read more
WaterField Designs Upgrades TSA-friendly Zip...
San Francisco based designer and manufacturer Waterfield Designs has unveiled an upgraded and refined Zip Brief. Ideal for the minimalist professional, the ultra-slim Zip laptop bag actually holds a... Read more
USB 3.0 Promoter Group Announces USB 3.2 Upda...
The USB 3.0 Promoter Group has announced the pending release of the USB 3.2 specification, an incremental update that defines multi-lane operation for new USB 3.2 hosts and devices. USB Developer... Read more
Save on MacBook Pros with Apple Refurbished 2...
Apple recently dropped prices on Certified Refurbished 2016 15″ and 13″ MacBook Pros with models now as much as $590 off original MSRP. An Apple one-year warranty is included with each model, and... Read more

Jobs Board

Frameworks Engineering Manager, *Apple* Wat...
Frameworks Engineering Manager, Apple Watch Job Number: 41632321 Santa Clara Valley, California, United States Posted: Jun. 15, 2017 Weekly Hours: 40.00 Job Summary Read more
Senior Software Engineer, *Apple* Online St...
Changing the world is all in a day's work at Apple . If you love innovation, here's your chance to make a career of it. You'll work hard. But the job comes with more Read more
Frameworks Engineering Manager, *Apple* Wat...
Frameworks Engineering Manager, Apple Watch Job Number: 41632321 Santa Clara Valley, California, United States Posted: Jun. 15, 2017 Weekly Hours: 40.00 Job Summary Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Frameworks Engineering Manager, *Apple* Wat...
Frameworks Engineering Manager, Apple Watch Job Number: 41632321 Santa Clara Valley, California, United States Posted: Jun. 15, 2017 Weekly Hours: 40.00 Job Summary Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.