【发布时间】:2021-12-19 23:40:14
【问题描述】:
我试图让 SDL2 在单击鼠标左键时输出鼠标的 x 和 y 坐标。程序以没有错误消息结束,但是当我左键单击时没有坐标输出到控制台。
#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;
}
我试过去掉 if 语句中的花括号,移动部分,但对我来说还没有任何效果。
【问题讨论】:
-
你能提供一个minimal reproducible example吗?值得注意的是,
SDL_Event event; // get all events这一行没有得到事件,它只是创建了一个未初始化的变量。您需要调用SDL_PollEvent或SDL_WaitEvent来填写事件数据。您的代码中可能有它,但在这里看不到。 -
@RetiredNinja 采纳了您的建议,将
SDL_Event event替换为SDL_PollEvent(&event)。但是,当我左键单击时没有输出坐标的问题仍然存在。我已经编辑了问题以包含程序中的更多代码 -
按钮按下的代码检查必须在您对
SDL_QUIT进行代码检查的事件循环内, -
@RetiredNinja 我尝试运行更新后的问题中的代码,但我仍然没有得到任何输出到控制台。
-
if (click.button == SDL_MOUSEBUTTONDOWN)不正确。SDL_MouseButtonEvent中的button变量是按钮的索引,如 0、1、2。请改用if (event.type == SDL_MOUSEBUTTONDOWN)。如果您愿意,您可以在此之后引用内部SDL_MouseButtonEvent,但是在您知道它是鼠标按钮事件之前访问它是一个问题。