14. Platformer

Believe it or not, this is basically the same as the scrolling right code. What makes a platform game different? Gravity. And we need a 16 bit X and Y speed and position. The lower byte represents sub pixel positions. I believe it’s called fixed point math. (I even splurged, and used a signed int or 2, gasp!).

Anyway, for gravity, we add a little to the Y speed every frame. Not too fast, or we might fall right through a floor. So we have a max allowable speed.

And moving left and right I’m slowly accelerating, up to a maximum speed. These define statements in the .h file control all this physics. It should be easy to fine tune now. These are 16 bit values, where the low byte is sub-pixel. So the max speed is really 2.25.

#define ACCEL 0x20 #define GRAVITY 0x50 #define MAX_SPEED 0x240 #define JUMP_VEL -0x600 #define MAX_RIGHT 0xb000

And I didn’t want all the platforms to act like solid brick walls. I wanted to be able to jump upward into the platform, but it would catch your feet. So, I added a collision array, which defines how each metatile behaves.

#define COL_DOWN 0x80 #define COL_ALL 0x40

const unsigned char is_solid[]={ 0, COL_DOWN, COL_ALL+COL_DOWN, COL_DOWN, COL_DOWN, COL_DOWN, 0, 0, 0, 0, 0, 0 };

I had to hand edit these, which is a bit awkward.

The BG collision code parses the collision bits, and sends a collision signal, depending on the direction. The main movement code ignores the feet collision if Y speed is negative (rising)

if(BoxGuy1.vel_y > 0) { BoxGuy1.vel_y = 0; }

And only sets feet collisions if the feet are just barely inside the block.

if((temp3 & 0x0f) > 3) collision_D = 0;

This is why it’s important that Y speed down can’t exceed 3 pixels per frame. Any faster, and you might miss the floor hit.

So I made some new blocks in NES Screen Tool, and screenshot to GIMP, save as metatiles.png, import that as a tileset to Tiled. Make some rooms. Export to .csv. Convert to C array. Import to the C code. (easy, right?)

Now it’s starting to feel like a real game.

https://github.com/nesdoug/17_Platformer

Last updated