Advertisement

!SDL_GetMouseState only works for button 1

Started by November 13, 2011 06:04 AM
1 comment, last by multiversicationist 13 years, 3 months ago
Hi. I'm a beginner learning SDL, and I noticed something which is bugging me.


alGetSourcei(source[3], AL_SOURCE_STATE, &val3);

if (SDL_GetMouseState(&x,&y)&SDL_BUTTON(1) && x<10 && y<10 && val3!=AL_PLAYING) alSourcePlay(source[3]);

else if (!SDL_GetMouseState(&x,&y)&SDL_BUTTON(1) && val3==AL_PLAYING){ alSourcePause(source[3]);}

This plays a sound file if the mouse cursor is in the upper left corner of the window and you press mouse button 1, and if you let off mouse button 1, the source is paused.

But when I use button 2, or 3 instead of 1, in the exact same code, the button press is registered, but the button release isn't, and the source will play, but not pause on release. Whats up with this?
I suspect it is an operator precendence issue. Logical NOT has a higher precendence than bitwise AND.

alGetSourcei(source[3], AL_SOURCE_STATE, &val3);

if ( (SDL_GetMouseState(&x,&y)&SDL_BUTTON(1)) && x<10 && y<10 && val3!=AL_PLAYING) alSourcePlay(source[3]);

else if (!SDL_GetMouseState(&x,&y)&SDL_BUTTON(1)) && val3==AL_PLAYING){ alSourcePause(source[3]);}


I generally try to avoid relying on precedence. by using parentheses or creating additional variables. The thing about relying on precendence is that once the code is written, it is hard to determine what the programmer intended the precendence to be, you can only see what they wrote.

I would write something like this:

alGetSourcei(source[3], AL_SOURCE_STATE, &currentState);

Uint8 button = SDL_GetMouseState(&mouseX, &mouseY)
if (button & SDL_BUTTON(1))
{
if(mouseX < 10 && mouseY < 10 && currentState != AL_PLAYING)
{
alSourcePlay(source[3]);
}
}
else if (currentState == AL_PLAYING)
{
alSourcePause(source[3]);
)
Advertisement

I suspect it is an operator precendence issue. Logical NOT has a higher precendence than bitwise AND.

alGetSourcei(source[3], AL_SOURCE_STATE, &val3);

if ( (SDL_GetMouseState(&x,&y)&SDL_BUTTON(1)) && x<10 && y<10 && val3!=AL_PLAYING) alSourcePlay(source[3]);

else if (!SDL_GetMouseState(&x,&y)&SDL_BUTTON(1)) && val3==AL_PLAYING){ alSourcePause(source[3]);}


I generally try to avoid relying on precedence. by using parentheses or creating additional variables. The thing about relying on precendence is that once the code is written, it is hard to determine what the programmer intended the precendence to be, you can only see what they wrote.

I would write something like this:

alGetSourcei(source[3], AL_SOURCE_STATE, &currentState);

Uint8 button = SDL_GetMouseState(&mouseX, &mouseY)
if (button & SDL_BUTTON(1))
{
if(mouseX < 10 && mouseY < 10 && currentState != AL_PLAYING)
{
alSourcePlay(source[3]);
}
}
else if (currentState == AL_PLAYING)
{
alSourcePause(source[3]);
)



Thanks man.

This topic is closed to new replies.

Advertisement