Search code examples
c++macossdl-2

SDL2 PointInRect If Statement not working


I'm making a little game as a small project but I can't get an if statement to do anything. If I make it !statement it works though. I run this if statement to find which cube on the "grid" (An array or cubes I render in a for loop I didn't show) the mouse clicked on. I use C++ and SDL2 on a Mac. This is my code:

#include <iostream>
#include <SDL2/SDL.h>

void RenderRects(SDL_Renderer *renderer);
void ToggleRect(int MouseX, int MouseY);

struct Grid
{
    bool IsActive;
    SDL_Rect Rect;

};

Grid grid[228960];

int main()
{

    bool IsRunning = true;
    bool IsRunningSim;
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window *window = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1000, 780, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    int h, w;
    
    SDL_MaximizeWindow(window);
    SDL_GetRendererOutputSize(renderer, &w, &h);

    
    while (IsRunning)
    {
        // std::cout << w << std::endl;
        // std::cout << h << std::endl;
        SDL_Event ev;
        while (SDL_PollEvent(&ev))
        {
            if (ev.type == SDL_QUIT)
            {
                IsRunning = false;
            }
            if (ev.type == SDL_MOUSEBUTTONDOWN)
            {
                int x, y;
                SDL_GetMouseState(&x, &y);
                ToggleRect(x, y);
            }
        }
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
        SDL_RenderClear(renderer);

        //rendering
        RenderRects(renderer);

        SDL_RenderPresent(renderer);
        
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

void RenderRects(SDL_Renderer *renderer)
{
    for (int i = 0; i < 1440; i += 10)
    {
        for (int j = 0; j < 795; j += 10)
        {
            SDL_Rect Rect = {i, j, 10, 10};
            grid[i].Rect = Rect;
            SDL_SetRenderDrawColor(renderer, 100, 100, 100, 225);
            SDL_RenderDrawRect(renderer, &grid[i].Rect);
        }
    }
}

void ToggleRect(int MouseX, int MouseY)
{
    
    SDL_Point MousePos;
    MousePos.x = MouseX;
    MousePos.y = MouseY;
    for (int i = 0; i < 228961; i++)
    {
        if (SDL_PointInRect(&MousePos, &grid[i].Rect)) //This is the if that doesn't work.
        {      
            std::cout << i << std::endl;
        }
       
    }
}

Solution

  • I have fixed this. I had to change my method of drawing since it was drawing over the rect and then showing after I changed its color. There was also an issue with generating the Rects that was probably effect it.