Source Code: Snap To Grid

This code shows how to snap the mouse coordinates to a 32 by 32 grid. It is perfect if you want to snap your player to a square, or to make a tilemap editor.

Requires: SDL
Link parameters (assuming MinGW compiler): -lmingw32 -lSDLmain -lSDL

#include <SDL/SDL.h>
 
const int WIDTH = 640;
const int HEIGHT = 480;
const int BPP = 32;
const int SQUARE_SIZE = 32;
 
int main(int argc, char* args[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
        return 1;
    }
    SDL_Surface *screen = SDL_SetVideoMode(WIDTH, HEIGHT, BPP, SDL_SWSURFACE);
    if (screen == NULL)
    {
        return 2;
    }
    SDL_WM_SetCaption("Snap to grid", NULL);
    SDL_ShowCursor( SDL_DISABLE );
 
    SDL_Event event;
    int x = 0, y = 0;
    bool isRunning = true;
    while (isRunning)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT ||
               (event.type == SDL_KEYDOWN && event.key.keysym.sym==SDLK_ESCAPE))
            {
                isRunning = false;
            }
            if (event.type == SDL_MOUSEMOTION)
            {
                x = event.motion.x;
                y = event.motion.y;
            }
        }
 
        // Square to be drawn
        SDL_Rect square;
        square.w = square.h = SQUARE_SIZE;
 
        SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF));
 
        // Draw chessboard pattern
        for (int idx = 0, x = 0; x < WIDTH; x += SQUARE_SIZE)
        {
            for (int y = 0; y < HEIGHT; y += SQUARE_SIZE, idx++)
            {
                square.x = x;
                square.y = y;
                if (idx % 2)
                {
                    SDL_FillRect(screen, &square, SDL_MapRGB(screen->format, 0xEE, 0xEE, 0xEE));
                }
            }
        }
 
        // Draw snapped square
        square.x = x / SQUARE_SIZE * SQUARE_SIZE;
        square.y = y / SQUARE_SIZE * SQUARE_SIZE;
        SDL_FillRect(screen, &square, SDL_MapRGB(screen->format, 0xAA, 0x0, 0xFF));
 
        // Draw square at mouse coords
        square.x = x - SQUARE_SIZE/2; // subtract hotspot so center of square is drawn at mouse coords
        square.y = y - SQUARE_SIZE/2;
        SDL_FillRect(screen, &square, SDL_MapRGB(screen->format, 0x55, 0x55, 0x99));
 
        if (SDL_Flip(screen) == -1)
        {
            return 3;
        }
    }
    SDL_Quit();
}
Categories: Source Code
page tags: source-code
page_revision: 2, last_edited: 1239856250|%e %b %Y, %H:%M %Z (%O ago)