Posted By: MasterQ32
Ultra Simple Platformer Script - 03/28/16 17:15
Just a small demonstration of how to create a simple platformer system with jumping and collision with platforms in 2D.
No use of any engine functions except for draw_quad and draw_line.
No use of any engine functions except for draw_quad and draw_line.
Code:
/** * Licence: * Public Domain */ #include <acknex.h> #include <keys.c> typedef struct { float x0, x1, y; } Platform; Platform platforms[10]; // Noteworthy information: // the game logic handles y coordinates in mathematical way: +y is up, -y is down. // y = 0 is the bottom of the screen // all coordinates are in pixels, pixels/tick or pixels/tickČ function main() { fps_max = 60; int i; // Initialize some random platforms for(i = 0; i < 10; i++) { platforms[i].x0 = random(screen_size.x - 64); platforms[i].x1 = platforms[i].x0 + 64; platforms[i].y = 64 + random(screen_size.y - 128); } wait(1); // Start on the first platform var playerX = 0.5 * (platforms[0].x0 + platforms[0].x1); var playerY = platforms[0].y; var velX = 0.0; var velY = 0.0; wait(1); while(1) { // move left/right if(key_cul) { velX -= 10 * time_step; } else if(key_cur) { velX += 10 * time_step; } // damp our movement a little so we will come to a stop velX *= 0.8; // Apply gravity velY -= 5 * time_step; // Check collision with each platform to disable downwards movement var isStanding = 0; for(i = 0; i < 10; i++) { // Check for left/right bound if((playerX + 10) < platforms[i].x0) { continue; } if((playerX - 10) > platforms[i].x1) { continue; } // If we are in range around the platform, we are standing on it if(abs(playerY - platforms[i].y) <= 1) { isStanding = 1; } // Extrapolate player movement in newY var oldY = playerY; var newY = playerY + velY * time_step; // If we start moving below the platform, just ignore the platform if(oldY < platforms[i].y) continue; // If we end moving above the platform, also ignore the platform if(newY > platforms[i].y) continue; // If we move from above the platform below the platform, we should collide with it: // Cheat ourselves to the platform top playerY = platforms[i].y; // Stop moving in vertical direction velY = 0.0; // We are also standing if we collided with the platform isStanding = 1; } if(isStanding == 1) { // Apply jump force if(key_hit("space")) velY += 32; } // Move our player playerX += velX * time_step; playerY += velY * time_step; // Draw the player. (playerX, playerY) is the center position of our players feet. draw_quad( NULL, vector(playerX - 10, screen_size.y - playerY - 40, 0), NULL, vector(20, 40, 0), NULL, COLOR_BLUE, 100, 0); // Draw each platform for(i = 0; i < 10; i++) { // this is engine specific, moves the drawing cursor draw_line(vector(platforms[i].x0, screen_size.y - platforms[i].y, 0), NULL, 100); draw_line(vector(platforms[i].x0, screen_size.y - platforms[i].y, 0), COLOR_RED, 100); draw_line(vector(platforms[i].x1, screen_size.y - platforms[i].y, 0), COLOR_RED, 100); } wait(1); } }