A sprite is no good unless it can do something; and to be honest a game is no good unless you write it in a structured way. This is the way I used to handle in-game sprite logic; it’s probably not too dissimilar to the way that other games programmers did it.
The trick is to have a small block of memory, say 16 bytes, that can be used to store sprite data, such as it’s position on screen, size, address of the code to move the sprite and some flags to determine it’s behaviour. It’s a bit like a sprite structure or class.
So, my class may look something like this:
Byte &00 Index into sprite graphic data Byte &01 X coordinate Byte &02 Y coordinate Byte &03 Width Byte &04 Height Byte &05,&06 Address of sprite handler routine Byte &07 Flags Byte &08-&0F Sprite Variables
A sprite position would be marked as “unused” if the handler address was set to &0000. The flags would contain useful bits, so bit 0 might be set if the sprite is deadly, 1 if the sprite was not to be drawn, etc. Sprite variables could be sprite specific, or not used at all.
I would decided upon the maximum number of sprites my game would require, say 32, and reserve an area of memory for the data; in this case 16 x 32 bytes (512).
Note that I usually like my numbers to be whole powers of 2. I’m afraid that this is due to exposure to too much binary in my formative years.
Anyway, I digress. The game routines would use this information to render the game, so:
- Adding a sprite would involve looping through the data until it found an empty slot (i.e. it’s handler address was set to &0000). The sprite information would then be added into that slot, or the routine would return that the maximum number of sprites are on screen.
- Removing a sprite would simply involve setting the sprites handler address to &0000.
- Drawing the sprites would involve looping through the data and rendering the sprites at the appropriate addresses.
- Checking for collisisions would loop through the data and compare one sprite against all the other sprites in the data.
- Moving the sprites would involve looping through the data and calling the handler routines. These handler routines would be passed the sprite block address and would typically modify it’s data, for example add 1 to the X coordinate.
And that’s about it for sprites. Like I said, it’s not really rocket science. I’ll be putting my last three blog posts into practice soon with a working sprite handler routine. I seem to be using balls in my examples, so it’ll probably just be a load of balls bouncing around on screen.