SDL鼠标事件无法正常工作

时间:2014-05-02 11:07:45

标签: c++ mouseevent sdl

当我在int main上面声明Button类时,我得到了正确的结果,但是当创建一个新类Button时,鼠标坐标是错误的。 这是我的代码:

class Button {
    public:
    SDL_Rect box;
    Button(int a, int b, int w, int h);
    Button(const Button& orig);
    virtual ~Button();
    void handle_events();
};

SDL_Event event1;

Button::Button(int x, int y, int w, int h) {
    //Set the button's attributes
    box.x = x;
    box.y = y;
    box.w = w;
    box.h = h;
}
void Button::handle_events() {

                    //Get the mouse offsets

                    int aa = event1.motion.x;
                    int bb = event1.motion.y;
                    printf("%d %d\n",aa,bb);
//...
}
..........
..........
SDL_Event event;
int main(){
Button test(431, 318, 81, 27);
if (SDL_PollEvent(&event)) {
play.handle_events();
}
return 0;
}

stdout.txt中的输出:
0 0
431 318
0 0 等等。 它应该返回鼠标的当前x,y而不是Button构造函数的前两个参数?

1 个答案:

答案 0 :(得分:1)

Button::handle_events()使用与您传递给SDL_PollEvent的变量不同的变量 - 即使名称不同。
我不确定为什么会改变其中一个影响另一个。

为什么不将它传递给函数,并避免所有混乱的全局变量:

void Button::handle_events(SDL_Event evt) {
    //Get the mouse offsets
    int aa = evt.motion.x;
    int bb = evt.motion.y;
    printf("%d %d\n",aa,bb);
}


// ...

if (SDL_PollEvent(&event)) {
    play.handle_events(event);
}

(我假设您正在定义" test",但在main中使用" play"这是一个错字。)

相关问题