Creating a simple Pong game using Raylib requires you to have a working development environment for Raylib set up on your system. Raylib is a C library, so you will need to have a C compiler (like GCC or Clang) and Raylib installed to compile and run this example code.
Below is a simple example of a Pong game written in C using the Raylib library. This code sets up a basic window, draws the paddles and ball, and handles basic input and collision detection.
c
#include "raylib.h"
int main() {
// Initialization
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "Pong Game - Raylib");
// Paddle variables
Rectangle leftPaddle = { 50, screenHeight / 2 - 50, 10, 100 };
Rectangle rightPaddle = { screenWidth - 60, screenHeight / 2 - 50, 10, 100 };
float paddleSpeed = 5.0f;
// Ball variables
Vector2 ballPosition = { screenWidth / 2, screenHeight / 2 };
Vector2 ballSpeed = { 4.0f, 4.0f };
int ballRadius = 5;
SetTargetFPS(60); // Set game to run at 60 frames-per-second
// Main game loop
while (!WindowShouldClose()) { // Detect window close button or ESC key
// Update
// Move the left paddle
if (IsKeyDown(KEY_W)) leftPaddle.y -= paddleSpeed;
if (IsKeyDown(KEY_S)) leftPaddle.y += paddleSpeed;
// Move the right paddle
if (IsKeyDown(KEY_UP)) rightPaddle.y -= paddleSpeed;
if (IsKeyDown(KEY_DOWN)) rightPaddle.y += paddleSpeed;
// Update the ball position
ballPosition.x += ballSpeed.x;
ballPosition.y += ballSpeed.y;
// Check for ball collision with top and bottom screen boundaries
if (ballPosition.y <= 0 || ballPosition.y >= screenHeight) {
ballSpeed.y *= -1;
}
// Check for ball collision with paddles
if (CheckCollisionCircleRec(ballPosition, ballRadius, leftPaddle) ||
CheckCollisionCircleRec(ballPosition, ballRadius, rightPaddle)) {
ballSpeed.x *= -1;
}
// Draw
BeginDrawing();
ClearBackground(RAYWHITE);
// Draw paddles
DrawRectangleRec(leftPaddle, BLACK);
DrawRectangleRec(rightPaddle, BLACK);
// Draw ball
DrawCircleV(ballPosition, ballRadius, BLACK);
EndDrawing();
}
// De-Initialization
CloseWindow(); // Close window and OpenGL context
return 0;
}
Compile this code with your C compiler (assuming you have named the file pong.c and have Raylib installed):
This command compiles the pong.c file and links it with the Raylib library and other required libraries for OpenGL, maths, threads, the dynamic linker, real-time extensions, and the X11 windowing system.
Run the compiled program:
sh
./pong
This simple Pong game has two paddles that can be moved up and down with the W and S keys for the left paddle, and the Up and Down arrow keys for the right paddle. The ball bounces off the top and bottom edges of the window and the paddles. The game continues as long as the window is open; it doesn't keep score or have a game over condition. You can add those features to make it a complete game.