Thursday, August 30, 2012
Petit Computer Platform Engine v1.0
Here it is -- the complete, 1.0 version of my Petite Computer platform game engine.
What this is not: A game kit. I have not tried to make this a generic game where you draw the levels and place monsters and items. Creating a game with this engine will take a lot of custom programming.
What this is: A head start. I wanted to make a framework that takes care of a lot of the tedious stuff that's common to most platform games. It gives you four-directional scrolling, gravity, moving platforms, and objects with customizable attributes. I wanted to make it as easy as possible for someone with some programming experience to get a foot in the door and make something working without getting mired down in the early mechanical details.
This engine is intended to be sliced, diced, and rebuilt to fit your idea and make the game you want to make.
To help you better understand it, here's a complete program listing with in-depth comments to explain exactly what's happening. This may not be the most efficient way to solve these problems, but it should give beginners some idea of the basics.
Clear the screen, clear the memory.
Petit Computer doesn't really have constants, so I'm keeping these important values in variables. You can, of course, change their values here if your program has different needs, and there may be reasons to modify them as the program runs, but these values are used to set the dimensions of important arrays, so it's a bad idea to let them get bigger than whatever initial value you set here.
MAPX and MAPY are the size of the level map, and they also affect the constraints of the camera. OBJ is the number of moving objects you want to have at one time.
Here's our level map.
The X and Y coordinates, respectively, of every object in the system. In a previous version, these coordinates were relative to the screen, but it proved to be a lot easier to define them as being relative to the level map. This allows us to keep track of off-screen objects and allow them to keep interacting with the level.
Note that object 0 is always the player character.
The X and Y velocities, respectively, of every object in the system. Negative velocities are up and to the left, positive velocities are down and to the right. All velocities are pixels per frame.
'1 - Pass through walls
'2 - Ignore gravity
'4 - Turn around at walls
'8 - Turn around at cliffs
'16 - Carry the player
'32 - Stop when offscreen
The FL array is for "flags". There are a number of special behaviors that occur a lot in platform games -- flying objects, moving platforms, and so on. I've included the code for these behaviors, and you can enable them by setting the FL value for each object in the system. These are bit flags, so you set the value by adding together the value for each behavior you want and use bitwise operators to see which are set for each object. For instance, if you want a bullet that goes through walls, you'll want to pass through walls and ignore gravity: 1+2=3.
Here's a complete explanation for the six different kinds of behavior. I'll show how they're actually implemented when we reach those points in the code.
Pass through walls
The default behavior is to check if moving a sprite causes it to overlap with a background element, and if so, to move it back away from the background element. If this flag is set, the object will not perform these checks. You can use this for ghost enemies, projectiles that pass through walls, and so on.
The default behavior is for every object to accelerate in the Y direction due to gravity at a rate of .1 pixels/frame^2. If this flag is set, the acceleration isn't applied. Objects that pass through walls will usually need this flag set too, otherwise they'll drop through the floor and out of the level. Good for flying objects.
Turn around at walls
The default behavior is for objects to stop (X velocity set to 0) if they run into a wall. If this flag is set, the object will instead turn around -- that is, the sign will be set so that the velocity is in the opposite direction of the wall. This is good for unintelligent creatures that just mill around aimlessly.
Turn around at cliffs
The default behavior is for objects to move straight forward at the rate of X velocity, straight off the edge of platforms. If this flag is set, the object will instead turn around when it reaches the end of a platform. This is good for unintelligent creatures that just stick to a single platform and defend it.
Carry the player
If this flag is set, the object will act as a platform for the player and carry the player object as it moves around. This is good for moving platforms.
Stop when offscreen
The default behavior is for all objects to update every frame. If this flag is set, the object will only update its position when it is actually onscreen. This is good for creating situations where the movement of enemies is important, and you want to make sure they're in a certain position when the player arrives; for example, an enemy that falls down from its platform to ambush the player shouldn't move until the player actually reaches that part of the level.
What follows are examples of how to set the initial positions and behaviors of four sprites.
Our first sprite starts at point (200,160). It has all of the flag behavior except stopping offscreen (1+2+4+8+16=31), so it ignores gravity and walls and it can carry the player. (The other two behaviors don't affect the way this object works because it ignores walls.) I set an initial Y velocity because, ignoring gravity, I need to specify this myself to get it to move.
Second sprite starts at (10,10). It turns around at walls and carries the player. (4+16=20) We set an initial X velocity to start it running.
Third sprite starts at (200,160). Its only abnormal behavior is turning around at the edge of platforms. (8)
Fourth sprite starts offscreen at (720,0). This one turns at walls and doesn't move unless it's onscreen.
You can run the program and observe the moving objects to confirm that this is the way they behave. Change the values of the flags to see how they can behave differently.
Note that we've only initialized sprites 1-4. Sprite 0, the player, has no modifications. Therefore, he'll begin at (0,0) with no unusual behavior.
We start the camera in the upper left corner of the level.
Setting the characters for our four sprites. I don't deal with animation in this demonstration because I decided that it's a tricky enough proposal that it's more useful for a programmer to custom-code it for the game he's creating than for me to try and generalize it in this engine.
FOR I=0 TO 10
FOR J=22 TO 23
FOR I=0 TO 60
FOR I=25 TO 31
FOR I=5 TO 18
FOR I=20 TO 127
FOR I=65 TO 127
Here, I'm just filling the map with blocks, character 44. Reading or generating level data is also left as an exercise for the programmer.
FOR I=0 TO 32
FOR J=0 TO 24
Before we begin the main loop, we fill the background with the first screen's worth of blocks.
RI keeps track of which moving platform the player is currently riding on. A 0 indicates none.
FOR TH=0 TO OBJ-1
We run this loop for every object in the system. TH is short for "this", the object we're currently dealing with.
We put the X and Y coordinates of the current object into X and Y, mostly to make the code easier to read.
Draw the sprite on the screen. Since X and Y are relative to the overall map, we subtract the X and Y offset of the camera to find their position on the screen.
C1=((FL(TH) AND 32)==32)
C2=(ABS(X-XOFS-120)>136) OR (ABS(Y-YOFS-88)>104)
IF C1 AND C2 THEN @PHYDONE
Here, I'm breaking down the conditions of my IF statement on multiple lines. I do this a bit to improve readability and to keep from pushing the 100 characters per line limit. Condition 1 is true if this object doesn't update when it's offscreen. Condition 2 is a tricky bit of math that only returns true if the X and Y coordinates fall outside the range -15 to 255 and -15 to 191, respectively -- in other words, if the object is offscreen. If both conditions are true, we skip to the bottom of the physics loop.
Update the object's Y position according to its velocity.
IF FL(TH) AND 2 THEN @SKIPGRAV
If the object ignores gravity, skip gravity acceleration.
Gravity acceleration, .1 pixels/frame^2.
IF SYV(TH)>2 THEN SYV(TH)=2
Terminal velocity, 2 pixels/frame.
Now we're going to check for vertical collisions with the background. CY keeps track of whether the Y direction is clear, and it's true until we hit something. G keeps track of whether this object has hit the ground, and H keeps track of whether this object has hit its "head".
(IX1,IY1) and (IX2,IY2) are the tiles at the top left and bottom right of this object, respectively.
AV=SYV(TH):IF TH==0 AND RYV!=0 THEN AV=RYV
We need to know the velocity of this object in the Y direction to decide which direction to check for collisions. Usually, this will just be SYV(TH). However, if the player is on a moving platform, the player's Y velocity may not be the actual direction that it's traveling. RYV holds the Y velocity of whatever sprite the player may be riding. So if TH=0 -- in other words, if we're doing this loop for the player object -- and RYV isn't 0 -- if the player actually is riding something -- then we use the velocity of the object the player is riding instead.
J=IY2:IF AV<0 j="IY1</p" then="then">
Based on the direction this object is moving, we check above or below for collisions.
FOR I=IX1 TO IX2
IF MAP(A,B)>0 THEN CY=FALSE
We loop through all of the possible tiles that the object may be colliding with. If there is a block in that position, then the Y direction isn't "clear".
Note the tricky math to determine which map element to check. This is because an object may travel beyond the boundaries of the map; if we use subscripts that are less than 0 or greater than MAPX-1 or MAPY-1, there will be no data to read, and the system will throw an error. To get around this, I use these tricks to force out of bounds values into in-bounds values without changing the value of in-bounds values.
What happens if an object is out of bounds? If the object travels right and down beyond the limits, it will seem as if the level has looped around to the left and top end, respectively. If the object travels left and up beyond the limits, it will seem as if the level has MIRRORED and start again in reverse.
Out of bounds values are essentially garbage. Good code should try to keep objects in bounds and deal with them quickly if they wander out (as into a bottomless pit).
IF FL(TH) AND 1 THEN CY=TRUE
If this object ignores walls, then we force the "clear" flag to read true regardless of the results of the test.
IF CY THEN @EDGE
If the way is clear, we skip down to edge detection.
IF AV<0 else="else" then="then" y="IY1*8:G=TRUE</p">SYV(TH)=2
If a collision was found, we bump the object up or down to the next map tile, depending on whether it was falling or rising. We also make note of whether the object is grounded or it hit its head. All vertical collisions result in resetting the Y velocity to 2 pixels/frame downward.
IF (FL(TH) AND 8)==0 THEN @HORIZ
If this object doesn't turn around at edges, we don't bother trying to check for them.
Taking a look at the lower-left and lower-right tiles that this object overlaps. L is true if there is a block to the left, and R is true if there is a block to the right.
IF L AND R==FALSE THEN SXV(TH)=-ABS(SXV(TH))
IF R AND L==FALSE THEN SXV(TH)=ABS(SXV(TH))
If there is a block to the left but not to the right, then we want to stop traveling to the right; we force our X velocity to go negative. Similarly, if there's a block to the right but not to the left, we don't want to travel to the left, so the velocity becomes positive.
IF TH==0 THEN GR=G:HH=H
If we're currently examining the player object, we want to store the checks that determined whether the player was grounded or hit its head because these become important for checks we make later.
Store the value of Y back into the object's coordinates, then update the X value for its X velocity. CX is true if the X direction is clear. P is true if the object is "pushing" against a wall.
AV=SXV(TH):IF TH==0 THEN AV=SXV(0)+RXV
IF AV==0 THEN @RIDE
I=IX1:IF AV>0 THEN I=IX2
FOR J=IY1 TO IY2
IF MAP(A,B)>0 THEN CX=FALSE:P=TRUE
These are the same sorts of checks we did before, this time looking in the X direction.
IF FL(TH) AND 1 THEN CX=TRUE
Again, if we ignore walls, we force CX to be true.
IF CX THEN @RIDE
IF FL(TH) AND 4 THEN SXV(TH)=-SXV(TH):GOTO @RIDE
If this object bounces off walls, we simply invert the X velocity when it reaches a wall and skip the rest of it.
IF AV>0 THEN X=IX1*8 ELSE X=(IX1+1)*8
We bump the object back to the last clear tile and stop it.
IF TH==0 THEN PU=P
Update the X coordinate, and if we're dealing with the player, keep track of whether it's "pushing" a wall.
R=((FL(TH) AND 16)==16) AND SPHITSP(0,TH) AND (SY(TH)-SY(0)>8) AND (SYV(0)>=0)
IF R AND (GR==FALSE OR SYV(TH)<0 and="and" hh="=FALSE" ri="TH</p" then="then">
Here, we're checking to see if the player object is riding this object. There are a colossal SIX conditions to check, and all of them must be met:
1) Is this object actually a platform? If it isn't, then naturally it's not going to carry the player.
2) Is this object touching the player?
3) Is the player 8 pixels higher than the object or more? I've played around with it, and this seems to be the threshold that allows a moving platform to "catch" the player without detecting some obvious misses.
4) Is the player falling? We don't want to catch the player on the way up from a jump.
5) Either of these conditions must be met: the player is not already standing on the ground, or the platform is moving up. This allows us to make platforms that can catch the player by moving up from the ground to meet it, but not by moving down into the ground.
6) The player is not hitting its head. If a platform carries the player up into a block and the player hits its head on it, the player should stop riding this platform and drop through.
When all of these conditions are met, we will consider the player to be riding this moving platform. If more than one object qualifies as the player's ride, we consider the one with the highest object number.
And we're done! Back to the top, check the next object.
IF SY(1)>200 THEN SYV(1)=-1
IF SY(1)<16 p="p" syv="syv" then="then">
Most object AI should be performed inside the TH loop. This will allow you to better generalize object behavior. If this were a real game, I would probably use the special variables associated with each sprite to keep track of what kind of thing each sprite is and use this information to dictate its behavior. Moreover, for specialized objects (like this moving platform), I would use the sprite variables to determine where it's allowed to move.
But since this example is so simple, I put the AI for the moving platform here. It simply checks the object's Y position and changes the direction it moves when it reaches certain boundaries.
IF RI==0 THEN @SKIPRIDE
Now we're going to deal with the player riding moving platforms. We start by clearing out the player's "riding" velocities. If we didn't find a platform for the player to ride on, we skip the next steps.
First, we position the player to make it look like it's standing neatly on top of whatever platform the player is riding on. Then, we move the player according to the horizontal velocity of that platform. Finally, we treat the player as if it is "grounded", so that it can jump and so on.
We take note of the X and Y velocities of the platform the player is riding (for use in the collision tests above), and we're done.
Scrolling the screen is rather complicated. It's moved down to a subroutine below to keep the main loop relatively clear.
Store the current state of the buttons.
IF BU AND 8 THEN SXV(0)=SXV(0)+.2
IF BU AND 4 THEN SXV(0)=SXV(0)-.2
If the user is holding left or right, we increase the X velocity in the appropriate direction.
IF (BT AND 32)==32 AND GR THEN SYV(0)=-2.25:BEEP 8,-4096
I prefer the Super Mario World controls (Y=Run, B=Jump) on a DS, so here, we check if the B button has been pressed and the player is standing on stable ground. Using the BTRIG() value instead of the BUTTON() value means that we'll only detect the press once; the player can't hold down the button to jump repeatedly.
To actually make the player jump, we simply give it an upward Y velocity and use BEEP to make the jumping noise.
IF (BU AND 32)==0 AND SYV(0)<0 p="p" syv="syv" then="then">
In Super Mario Brothers, the height of Mario's jump depends on how long you hold down the jump button. Here's how to make that work. If the B button isn't being held down and the player is rising, we simply kill the player's upward velocity, exactly as if it had reached the height of its jump and started falling again.
The next three lines allow you to add a "wall jump" to the player's move set. Not every game is going to want wall jumps, so the lines are commented out to indicate that they're optional. If you want wall jumps in your game, remove the apostrophes at the beginning of each line. If you don't, you can remove the three lines altogether to save space.
'WJ=(GR==FALSE) AND (PU==TRUE) AND ((BT AND 32)==32)
A wall jump is valid if all three conditions are true: the player is not standing on solid ground, the player is pushing up against a wall, and the user has pressed the jump button.
'IF (BU AND 4)==4 AND WJ THEN SXV(0)=2:SYV(0)=-2.25:BEEP 8,-4096
'IF (BU AND 8)==8 AND WJ THEN SXV(0)=-2:SYV(0)=-2.25:BEEP 8,-4096
If a wall jump is valid, we do the jump. The Y velocity and BEEP are the same as before, but we also add an X velocity according to which direction the user is pushing to kick the player away from the wall.
L=1 IF SXV(0)<0 l="-1</p" then="then">IF BU AND 128 THEN L=L*2
Calculating the maximum X velocity of the player. If the player is moving left, the velocity will be negative, otherwise it will be positive. If the user is holding down the Y button, we'll allow the maximum to be doubled.
IF ABS(SXV(0))>ABS(L) THEN SXV(0)=L
If we've broken the limit, we go back down to the limit.
IF SXV(0)>0 THEN SXV(0)=SXV(0)-.1
IF SXV(0)<0 p="p" sxv="sxv" then="then">
Friction. If the player is moving right, we pull him back to the left. If the player is moving left, we pull him back to the right.
IF ABS(SXV(0))<.1 THEN SXV(0)=0
Decimal math is very imprecise in this system, which sometimes leads to very small fractions of velocity. Here, we just detect those small fractions we don't want and return them to zero.
VSYNC 1 tells the system to wait until it's time to draw the next frame. Then we return to the top of the main loop and start again.
Now we're going to look at how the screen scrolls. It helps if you know, before you begin, how the background is represented. Here's my explanation of the background, copied and pasted from the comments in the last version. Big thanks to GameFAQs forum user UncleSporky for his scrolling screen demonstration, which helped me to learn how this all works.
First, think of the background as a grid of tiles, 64x64, with X and Y coordinates numbered 0 to 63. Each tile in this grid is 8 pixels by 8 pixels, so you can also think of the background as a grid of pixels, 512x512.
The screen only shows a small part of this background, 32 tiles horizontally and 24 vertically. So we also have a "camera" which we can move around to show different parts of the screen. The camera can move pixel by pixel, so the screen isn't always going to be exactly lined up with the background tiles. If you think of the background as a grid of pixels, then the camera's "offset" would be the coordinates of the top left pixel of the screen relative to the background.
Once you've got your head around that idea, you should understand that the background wraps around, both horizontally and vertically. This means that when you refer to background tile (64,64), you will actually be referring to tile (0,0). Likewise, camera offset (512,512) is the same as (0,0).
This is incredibly valuable. It means that we can treat the background as if it was ridiculously long in all directions. Take our map for example. We want to tell the system "Put the character from MAP(X,Y) onto tile (X,Y) of the background." As we scroll to the right, X goes from 0 to 127. When X is from 0 to 63, we write to the background X from 0 to 63. When X is 64, we just keep scrolling, but now we're writing to the background X starting at 0 again. This works because, by this point, we're not displaying what we originally had at background X 0 anymore; it's already scrolled off to the left.
The basic strategy is this:
Start by drawing the initial state of the screen.
When it's time to scroll, assume that the tiles you're about to scroll into are garbage and overwrite them with the correct values.
As long as you follow those two rules, you can scroll the screen out for a very, very long time. (You'll eventually get overflow errors when X and Y get out to about 500,000 or so; luckily, this program doesn't get up that high.)
Start by figuring out which tile of the background the camera is pointing at. We'll use this to determine if the camera has gone past a tile boundary.
Calculating the maximum X and Y coordinates for the camera.
Here, we figure out where on the screen the player is. We don't need the screen to be completely centered on the player at all times, so I've determined some "scroll zones"; if the player moves beyond a certain place in the screen, the screen will try to scroll to show what lies ahead.
IF X<=136 OR XOFS>=MAXX THEN @S2
We skip the scrolling if the player hasn't entered the right scroll area, or if the camera has already reached its limit.
We figure out how far into the scroll zone the player has moved, and bump the camera to the right that many pixels.
IF XOFS>MAXX THEN XOFS=MAXX
If we moved the camera too far, we bump it back into place.
IF FLOOR(XOFS/8)<=MX THEN @S2
If we haven't crossed a tile boundary, we skip the next step.
FOR I=0 TO 24
Drawing the next column of tiles as we scroll into them. Again, note the use of modulo math to keep our values within the proper range. The background beyond the right and bottom edges of the map will essentially be filled with garbage data, but the camera will never scroll far enough to show it.
IF X>=120 OR XOFS<=0 THEN @S3
IF XOFS<0 then="then" xofs="0</p">IF FLOOR(XOFS/8)>=MX THEN @S3
FOR I=0 TO 24
The same ideas as above, but scrolling left.
IF Y<=164 OR YOFS>=MAXY THEN @S4
IF YOFS>MAXY THEN YOFS=MAXY
IF FLOOR(YOFS/8)<=MY THEN @S4
FOR I=0 TO 32
IF Y>=66 OR YOFS<=0 THEN @S5
IF YOFS<0 then="then" yofs="0</p">IF FLOOR(YOFS/8)>=MY THEN @S5
FOR I=0 TO 32
Finally, we move the camera into the correct position, and return.
How do you set a background? I'm trying to learn programming, and am messing around with this. The only way I know is by using SCRED, but that means you can't see the platforms and they don't behave properly either -- I think it breaks the scrolling...
I just added:
at the start.
I just added:
at the start.
By the way, this tutorial taught me a ton about scrolling maps and general collision detection. I just wanted to thank you for taking the time to do this!
how do you make a loop in a program? I need to keep the title screen running so it don't just end the title screenPost a Comment