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

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.