kolbalt
kolbalt

Reputation: 1

If statement in SDL2 is not outputting to the console

I am trying to make SDL2 output the x and y coordinates of the mouse when the left mouse button is clicked. The program ends with no error messages, however no coordinates are outputted to the console when I left click.

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

#include "Math.h"
#include "RenderWindow.hpp"

int main(int argc, char* args[])
{

SDL_Event event; // get all events

    if (SDL_Init(SDL_INIT_VIDEO) > 0) // error checks
        std::cout << "HEY.. SDL_Init HAS FAILED. SDL_ERROR: " << SDL_GetError() << std::endl;

    if (!(IMG_Init(IMG_INIT_PNG)))
        std::cout << "IMG_init has failed. Error: " << SDL_GetError() << std::endl;

    RenderWindow window("project v1.0", 1280, 720);

    SDL_Texture* backroundTexture = window.loadTexture("res/gfx/backround.png");  

    bool projRunning = true;

    while (projRunning) // quit
    {

        while (SDL_PollEvent(&event)) // when close event occurs
        {
            int x, y;
            SDL_GetMouseState(&x, &y);
            const SDL_MouseButtonEvent &click = event.button; // recognize mouse button events

            if (click.button == SDL_MOUSEBUTTONDOWN) // detect when left mouse button is pressed
            {
                std::cout << "X = " << event.button.x << std::endl;
                std::cout << "Y = " << event.button.y << std::endl;
                break;
            }

            if (event.type == SDL_QUIT)
                projRunning = false;
        }

        window.clear(); // cleanup
        window.render(backroundTexture);
        window.display();

    }

    window.cleanUp();
    SDL_Quit();

    return 0;
}

I have tried taking away the curly braces in the if statement, moving parts around, but nothing has yet worked for me.

Upvotes: 0

Views: 159

Answers (1)

Lev M.
Lev M.

Reputation: 6269

Simply declaring a SDL_Event variable is not going to capture any events.

The reason your program does not enter the if block, is because event.button is never initialized, so the condition is always false.

To get input and other events using SDL you need to setup an event loop in your code, like so:

SDL_Event event;

while (SDL_PollEvent(&event)) {
    if (event.type == SDL_MOUSEBUTTONDOWN) {
        std::cout << "X = " << event.button.x << std::endl;
        std::cout << "Y = " << event.button.y << std::endl;
        break;
    }
}

Read more here: https://wiki.libsdl.org/SDL_Event

Upvotes: 2

Related Questions