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

Introduction

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
p=app.resourceFork.getcicn(1280)
GoodGuySprite=SpriteSurface1.NewSprite(p,32,32)
GoodGuySprite.x=300
GoodGuySprite.y=435
GoodGuySprite.group=1

//init the gunfire
p=app.resourceFork.getcicn(1300)
GunSprite=SpriteSurface1.NewSprite(p,32,32)
GunSprite.x=-200
GunSprite.y=467
GunSprite.group=2
gunvisible=false

//init the bad guys
p=app.resourceFork.getcicn(1290)
for i=1 to 10
BadguySprite(i)=SpriteSurface1.NewSprite(p,32,32)
BadguySprite(i).x=rnd*600
BadguySprite(i).y=rnd*200-250
BadguySprite(i).group=3
next

NumOfBadGuys=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
GoodGuySprite.close
end if
//kill the GunSprite
if GunSprite<>nil then
GunSprite.close
end if
//kill the BadguySprites
for i=1 to 10
if BadguySprite(i)<>nil then
BadguySprite(i).close
end if
next
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
p=app.resourceFork.getcicn(1300)
GunSprite=SpriteSurface1.NewSprite(p,32,32)
GunSprite.x=-200
GunSprite.y=467
GunSprite.group=2
gunvisible=false
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()
me.top=0
me.left=0
me.width=screen(0).width
me.height=screen(0).height
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
ClearAllSprites
InitSprites
SpriteSurface1.run
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.play. 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
me.graphics.forecolor=rgb(0,0,100)
me.graphics.fillrect 150+leftEdge,467+topEdge,40,13
me.graphics.forecolor=rgb(255,255,255)
me.graphics.textfont="Geneva"
me.graphics.textsize=10
// ! put the following code all on one line !
me.graphics.drawstring "Bad Guys Remaining: " + str(NumOfBadGuys), 50+leftEdge,477+topEdge

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

if me.keyTest(49) then //fire=spacebar
//shoot the gun
ShootingSound.play
if gunvisible=false then
//init the gunfire position here
GunSprite.x=GoodGuySprite.x+12
GunSprite.y=GoodGuySprite.y
gunvisible=true
end if
end if

//now check the position of gun only if it's turned on
if gunvisible=true then
GunSprite.y=GunSprite.y-30
//if the gun has reached the top of the screen
//hide it again and turn it off
if GunSprite.y<0 then
GunSprite.x=-200
GunSprite.y=447
gunvisible=false
end if
end if
    
//advance the badguys  
for i=1 to 10
//this is the speed of descent (increase for faster movement)
BadguySprite(i).y=BadguySprite(i).y+5
//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
BadguySprite(i).x=rnd*600
BadguySprite(i).y=40
end if
next

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 s1.group=2 and s2.group=3 then
BadGuyCrashSound.play
s1.close
s2.close
RemakeGun // since we killed the gun sprite, init it again
NumOfBadGuys=NumOfBadGuys-1
if NumOfBadGuys=0 then
s1.close
s2.close
spritesurface1.close
Statictext1.text="You Win!"
CheeringSound.play
end if
end if

//GoodguySprite and BadguySprite have collided
if s1.group=1 and s2.group=3 then
s1.close
s2.close
spritesurface1.close
Statictext1.text="You Lose!"
GoodGuyCrashSound.play
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.forecolor=rgb(0,0,100)
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)
me.surfacetop=topEdge
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.

Conclusions

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.

References


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

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Tor Browser 12.5.5 - Anonymize Web brows...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Malwarebytes 4.21.9.5141 - Adware remova...
Malwarebytes (was AdwareMedic) helps you get your Mac experience back. Malwarebytes scans for and removes code that degrades system performance or attacks your system. Making your Mac once again your... Read more
TinkerTool 9.5 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Paragon NTFS 15.11.839 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Apple Safari 17 - Apple's Web brows...
Apple Safari is Apple's web browser that comes bundled with the most recent macOS. Safari is faster and more energy efficient than other browsers, so sites are more responsive and your notebook... Read more
Firefox 118.0 - Fast, safe Web browser.
Firefox offers a fast, safe Web browsing experience. Browse quickly, securely, and effortlessly. With its industry-leading features, Firefox is the choice of Web development professionals and casual... Read more
ClamXAV 3.6.1 - Virus checker based on C...
ClamXAV is a popular virus checker for OS X. Time to take control ClamXAV keeps threats at bay and puts you firmly in charge of your Mac’s security. Scan a specific file or your entire hard drive.... Read more
SuperDuper! 3.8 - Advanced disk cloning/...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" - useful when you want to move all your data from one machine to another, or do a... Read more
Alfred 5.1.3 - Quick launcher for apps a...
Alfred is an award-winning productivity application for OS X. Alfred saves you time when you search for files online or on your Mac. Be more productive with hotkeys, keywords, and file actions at... Read more
Sketch 98.3 - Design app for UX/UI for i...
Sketch is an innovative and fresh look at vector drawing. Its intentionally minimalist design is based upon a drawing space of unlimited size and layers, free of palettes, panels, menus, windows, and... Read more

Latest Forum Discussions

See All

Listener Emails and the iPhone 15! – The...
In this week’s episode of The TouchArcade Show we finally get to a backlog of emails that have been hanging out in our inbox for, oh, about a month or so. We love getting emails as they always lead to interesting discussion about a variety of topics... | Read more »
TouchArcade Game of the Week: ‘Cypher 00...
This doesn’t happen too often, but occasionally there will be an Apple Arcade game that I adore so much I just have to pick it as the Game of the Week. Well, here we are, and Cypher 007 is one of those games. The big key point here is that Cypher... | Read more »
SwitchArcade Round-Up: ‘EA Sports FC 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 29th, 2023. In today’s article, we’ve got a ton of news to go over. Just a lot going on today, I suppose. After that, there are quite a few new releases to look at... | Read more »
‘Storyteller’ Mobile Review – Perfect fo...
I first played Daniel Benmergui’s Storyteller (Free) through its Nintendo Switch and Steam releases. Read my original review of it here. Since then, a lot of friends who played the game enjoyed it, but thought it was overpriced given the short... | Read more »
An Interview with the Legendary Yu Suzuk...
One of the cool things about my job is that every once in a while, I get to talk to the people behind the games. It’s always a pleasure. Well, today we have a really special one for you, dear friends. Mr. Yu Suzuki of Ys Net, the force behind such... | Read more »
New ‘Marvel Snap’ Update Has Balance Adj...
As we wait for the information on the new season to drop, we shall have to content ourselves with looking at the latest update to Marvel Snap (Free). It’s just a balance update, but it makes some very big changes that combined with the arrival of... | Read more »
‘Honkai Star Rail’ Version 1.4 Update Re...
At Sony’s recently-aired presentation, HoYoverse announced the Honkai Star Rail (Free) PS5 release date. Most people speculated that the next major update would arrive alongside the PS5 release. | Read more »
‘Omniheroes’ Major Update “Tide’s Cadenc...
What secrets do the depths of the sea hold? Omniheroes is revealing the mysteries of the deep with its latest “Tide’s Cadence" update, where you can look forward to scoring a free Valkyrie and limited skin among other login rewards like the 2nd... | Read more »
Recruit yourself some run-and-gun royalt...
It is always nice to see the return of a series that has lost a bit of its global staying power, and thanks to Lilith Games' latest collaboration, Warpath will be playing host the the run-and-gun legend that is Metal Slug 3. [Read more] | Read more »
‘The Elder Scrolls: Castles’ Is Availabl...
Back when Fallout Shelter (Free) released on mobile, and eventually hit consoles and PC, I didn’t think it would lead to something similar for The Elder Scrolls, but here we are. The Elder Scrolls: Castles is a new simulation game from Bethesda... | Read more »

Price Scanner via MacPrices.net

Clearance M1 Max Mac Studio available today a...
Apple has clearance M1 Max Mac Studios available in their Certified Refurbished store for $270 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Apple continues to offer 24-inch iMacs for up...
Apple has a full range of 24-inch M1 iMacs available today in their Certified Refurbished store. Models are available starting at only $1099 and range up to $260 off original MSRP. Each iMac is in... Read more
Final weekend for Apple’s 2023 Back to School...
This is the final weekend for Apple’s Back to School Promotion 2023. It remains active until Monday, October 2nd. Education customers receive a free $150 Apple Gift Card with the purchase of a new... Read more
Apple drops prices on refurbished 13-inch M2...
Apple has dropped prices on standard-configuration 13″ M2 MacBook Pros, Certified Refurbished, to as low as $1099 and ranging up to $230 off MSRP. These are the cheapest 13″ M2 MacBook Pros for sale... Read more
14-inch M2 Max MacBook Pro on sale for $300 o...
B&H Photo has the Space Gray 14″ 30-Core GPU M2 Max MacBook Pro in stock and on sale today for $2799 including free 1-2 day shipping. Their price is $300 off Apple’s MSRP, and it’s the lowest... Read more
Apple is now selling Certified Refurbished M2...
Apple has added a full line of standard-configuration M2 Max and M2 Ultra Mac Studios available in their Certified Refurbished section starting at only $1699 and ranging up to $600 off MSRP. Each Mac... Read more
New sale: 13-inch M2 MacBook Airs starting at...
B&H Photo has 13″ MacBook Airs with M2 CPUs in stock today and on sale for $200 off Apple’s MSRP with prices available starting at only $899. Free 1-2 day delivery is available to most US... Read more
Apple has all 15-inch M2 MacBook Airs in stoc...
Apple has Certified Refurbished 15″ M2 MacBook Airs in stock today starting at only $1099 and ranging up to $230 off MSRP. These are the cheapest M2-powered 15″ MacBook Airs for sale today at Apple.... Read more
In stock: Clearance M1 Ultra Mac Studios for...
Apple has clearance M1 Ultra Mac Studios available in their Certified Refurbished store for $540 off original MSRP. Each Mac Studio comes with Apple’s one-year warranty, and shipping is free: – Mac... Read more
Back on sale: Apple’s M2 Mac minis for $100 o...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $100 –... Read more

Jobs Board

Licensed Dental Hygienist - *Apple* River -...
Park Dental Apple River in Somerset, WI is seeking a compassionate, professional Dental Hygienist to join our team-oriented practice. COMPETITIVE PAY AND SIGN-ON Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Sep 30, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* / Mac Administrator - JAMF - Amentum...
Amentum is seeking an ** Apple / Mac Administrator - JAMF** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Child Care Teacher - Glenda Drive/ *Apple* V...
Child Care Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.