How to create a box that move like the ball in pong game using SDL2 in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <SDL.h>

const int WIDTH = 700;
const int HEIGHT = 600;
const int RECT_SIZE = 30;

typedef struct Box {
    int x, y;
    float xSpeed, ySpeed;
    int size;
} Box;

static Box box;

static SDL_Window* window = NULL;
static SDL_Renderer* renderer = NULL;

Box CreateBox(int size) {
    const float SPEED = 150;
    Box box = {
        .x = WIDTH / 2 - size / 2,
        .y = HEIGHT / 2 - size / 2,
        .size = size,
        .xSpeed = SPEED, 
        .ySpeed = SPEED, 
    };
    return box;
}

bool initialize(void) {
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError());
        return false;
    }

    window = SDL_CreateWindow("SDL",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
    if (!window) {
        return false;
    }

    renderer = SDL_CreateRenderer(window, -1,
        SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    box = CreateBox(RECT_SIZE);

    return true;
}

void RenderBox(const Box* box) {
    SDL_Rect rect = {
        .x = (int)box->x - box->size / 2,
        .y = (int)box->y - box->size / 2,
        .w = box->size,
        .h = box->size,
    };

    SDL_SetRenderDrawColor(renderer, 20, 50, 200, 32);
    SDL_RenderFillRect(renderer, &rect);
}

void UpdateBoxXYSpeed(Box* box, float elapsed) {
    box->x += (int)(box->xSpeed * elapsed);
    box->y += (int)(box->ySpeed * elapsed);

    if (box->x < RECT_SIZE / 2) {
        box->xSpeed = (float)fabs(box->xSpeed);
    }
    if (box->x > WIDTH - RECT_SIZE / 2) {
        box->xSpeed = (float)-fabs(box->xSpeed);
    }

    if (box->y < RECT_SIZE / 2) {
        box->ySpeed = (float)fabs(box->ySpeed);
    }
    if (box->y > HEIGHT - RECT_SIZE / 2) {
        box->ySpeed = (float)-fabs(box->ySpeed);
    }
}

void play(float elapsed) {
    SDL_SetRenderDrawColor(renderer, 0, 255, 200, 32);
    SDL_RenderClear(renderer);

    UpdateBoxXYSpeed(&box, elapsed);
    RenderBox(&box);

    SDL_RenderPresent(renderer);
}

void quit(void) {
    if (renderer)
        SDL_DestroyRenderer(renderer);
    if (window)
        SDL_DestroyWindow(window);
    SDL_Quit();
}

int main(int argc, char* argv[]) {
    atexit(quit);

    if (!initialize()) {
        exit(1);
    }

    bool quit = false;
    SDL_Event event;

    Uint32 lastTick = SDL_GetTicks();

    while (!quit) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }

        Uint32 currentTick = SDL_GetTicks();
        float elapsed = (currentTick - lastTick) / 500.0f;
        play(elapsed); 
        lastTick = currentTick;
    }

    return 0;
}

 



answered Mar 4, 2022 by avibootz
...