Hallo.
Last compo I wrote a platformer.
This took an unusually long amount of time.
This worries me for the next one coming up, so I’ve decided I might commit myself to simply using old code (as allowed by ‘base code’, although I’m going to try to confirm this specifically with as many LD’ers as I can before the compo).
Code:
player_x and player_y are float values, of the center of the player (which is a 16×16 box).
player_vspeed and player_hspeed correspond to the vertical and horizontal speed of the player (in pixels/frame).
current_map is a two dimensional boolean array, where true corresponds to a block and false not.
(Written with Processing.org in mind; any math functions such as min / max can be referenced through the Math java library, or really any programming language’s math library).
Up/down/left/right are booleans corresponding to the pressed-state of the cardinal keys, used for movement.
int LX = int((player_x-5)/16);
int LY = int((player_y+12)/16);
int RX = int((player_x+5)/16);
int RY = int((player_y+12)/16);
int MY = int((player_y+5)/16);
int TY = int((player_y-8)/16);
if ( (current_map[RX][RY] || current_map[LX][LY]) && player_vspeed > 0 )
{
player_vspeed = 0;
player_y = RY*16-12;
}
if (current_map[RX][RY] || current_map[LX][LY] )
{
//On ground.
if (up)
{
up = false;
player_vspeed = -5; //Jump speed.
}
if (!left && !right)
{
player_hspeed = player_hspeed * 0.8; //Horizontal velocity damping.
}
if (left)
{
player_hspeed = max(-3,player_hspeed - 0.3); //Accelerate to the left, with a maximum speed.
}
if (right)
{
player_hspeed = min(3,player_hspeed + 0.3); //Accelerate to the right, with a maximum speed.
}
}
else
{
player_vspeed = player_vspeed + 0.3; //Gravity. Accelerate down.
//In air.
if (left)
{
player_hspeed = max(-3,player_hspeed - 0.1); //For, in the air, horizontal acceleration from arrow keys.
}
if (right)
{
player_hspeed = min(3,player_hspeed + 0.1);
}
}
if (current_map[RX][TY] || current_map[LX][TY] )
{
player_vspeed = 0;
player_y = player_y + 2; //Hit the floor.
}
if (current_map[int((player_x+8.1)/16)][MY] && player_hspeed >= 0)
{
player_x = int((player_x+8.1)/16)*16-8.2;
player_hspeed = 0; //Hit a wall.
}
if (current_map[int((player_x-8.1)/16)][MY] && player_hspeed <= 0)
{
player_x = int((player_x-8.1)/16)*16 + 24.2;
player_hspeed = 0; //Hit a wall.
}
player_y = player_y + player_vspeed; //Accelerate the player.
player_x = player_x + player_hspeed;
player_vspeed = min(player_vspeed,5);