Joystick won't work using SDL - events

I'm building a simple game in SDL. I've been through countless tutorials and I've clearly missed something as it still ignoring my Joystick completely
In my constructor
SDL_JoystickEventState(SDL_ENABLE);
joystick = SDL_JoystickOpen(0);
In my update I'm calling a test to check I have actually initialized the joystick
if (SDL_NumJoysticks() <= 0)
{
done = true;
}
Here is my player update as well
void World::playerMovement()
{
SDL_Event event;
while (SDL_PollEvent (&event))
{
switch (event.type)
{
case SDL_QUIT:
done = true;
break;
case SDL_JOYAXISMOTION:
if ( ( event.jaxis.value < -3200 ) || (event.jaxis.value > 3200 ) )
{
test = true;
}
break;
}
}
}
Test is simply a bool which once true will mean my enemies start spawning. I also run a check in main
if (SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0)
{
fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
done = true;
}
When I run the game it loads as normal but no matter how much I move the joystick it won't set test to true.
I also tried using the following in the while poll event loop instead.
if (event.type == SDL_JOYAXISMOTION)
{
if(SDL_JoystickGetAxis(joystick, 1) > 0)
{
test = true;
}
}
Any idea's what I have missed?

I think emartel has the best answer to make sure SDL_joystick is working.
When does World::playerMovement() happen? The overall flow of your program is hard to determine from these snippets.
I'm happy to share with you my code for handling joysticks, which keeps track of: multiple joysticks, axes scaled [-1,1] with deadzone removed, and buttons held down.
http://www.raptor007.com/code/RaptorEngine_Joystick.zip
And here's a snippet of how that would be utilized as part of your main loop:
// FIXME: SDL needs to be initialized before we get here.
JoystickManager Joy;
Joy.Initialize();
double deadzone = 0.02;
// Main loop.
bool done = false;
while( ! done )
{
// Keep the list of joysticks up-to-date.
Joy.FindJoysticks();
// Handle all user input.
SDL_Event event;
while( SDL_PollEvent( &event ) )
{
// Let the JoystickManager track events relevant to it.
Joy.TrackEvent( &event );
// FIXME: Handle single-press events here (next target, etc).
// Don't handle button-held-down events like firing (see below).
if( event.type == SDL_QUIT )
done = true;
}
// Read joystick 0 analog axes.
double roll = Joy.Axis( 0, 0, deadzone );
double pitch = Joy.Axis( 0, 1, deadzone );
double yaw = Joy.Axis( 0, 3, deadzone );
double throttle = Joy.AxisScaled( 0, 2, 1., 0., 0., deadzone );
// Read joystick 0 buttons held down.
bool firing = Joy.ButtonDown( 0, 0 );
// FIXME: Update game objects and draw graphics.
}

I found a weird behaviour in SDL2:
If no events are put into the queue, try adding the following before the SDL_Init call:
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS,"1");

Are you sure joystick points to a valid joystick?
You state that you're getting it in your Constructor... does that contructor happen to be called before you initialize SDL with SDL_INIT_JOYSTICK? This could happen if your player is a global variable.
Make sure that in order you:
Init the Joystick subsystem, either by adding it to your SDL_Init with | SDL_INIT_JOYSTICK or by calling SDL_InitSubSystem(SDL_INIT_JOYSTICK);
Check SDL_NumJoysticks() > 0
Get joystick 0: joystick = SDL_JoystickOpen(0);
Enable events: SDL_JoystickEventState(SDL_ENABLE);
Process your events with SDL_PollEvent
At the end of your program, close your joystick: SDL_JoystickClose(joystick);
Also, make sure the joystick is properly detected in Windows and reports its inputs properly.

Looks like your SDL isn't init proper.
replace
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)
with
SDL_Init(SDL_INIT_EVERYTHING)

Is this SDL 1.2 or 2.0? In my case, on 2.0 SDL_PollEvent(&event) didn't actually put any data in the event struct. After that call, I had to use SDL_JoystickGetAxis(joystick_id, axis) and friends to get data.
So in your case, try to move the SDL_JoystickGetAxis call out of the if-test on event-type.

If you call SDL_NumJoysticks to get the number of controllers connected, then call SDL_JoystickOpen which returns a joystick identifier before your game loop then you will receive the SDL_JOYAXISMOTION events.
e.g.
int num_joy;
num_joy = SDL_NumJoysticks();
printf("%d joysticks found\n", num_joy);
for(int i = 0; i < num_joy; i++)
{
SDL_Joystick *joystick = SDL_JoystickOpen(i);
printf("Joystick name: %s\n", SDL_JoystickName(joystick));
}
SDL_Event event;
bool quit = false;
// Game loop
while(!quit)
{
// event loop
while(SDL_PollEvent(&event))
{
if (event.type == SDL_JOYAXISMOTION)
{
printf("Joystick______EVENT!\n");
}
// etc.....
See https://wiki.libsdl.org/SDL_JoystickName

I do not know how this can help you, but I do know that pygame supports joystick. And pygame is the python port of the SDL library. If everything fails, I guess you can always write that particular piece of code in python.

Related

I want to create an object at a position where there is nothing, but there is something wrong

I'm making a game in Unity2D where are 4 roads that tanks drive on, tanks spawn in random positions, I want to make sure that a tank can't spawn in a position that another tank is already in. When I start the game the Unity Editor crashes I think there is a problem somewhere in the do while loop but I haven't found it, hoping I described it right.
Thanks.
{
public GameObject tank;
public float spawnTime = 1f;
float positionX;
float positionY;
private bool check;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("TankSpawn", 1f, spawnTime);
}
void TankSpawn()
{
do
{
int rndY = Random.Range(1, 5);
float rndX = Random.Range(20.5f, 35.0f);
if (rndY == 1)
{
positionY = -3.5f;
positionX = rndX;
}
else if (rndY == 2)
{
positionY = 0.5f;
positionX = rndX;
}
else if (rndY == 3)
{
positionY = 4.5f;
positionX = rndX;
}
else if (rndY == 4)
{
positionY = 8.5f;
positionX = rndX;
}
GameObject[] tanks = GameObject.FindGameObjectsWithTag("tank");
foreach (GameObject tank in tanks)
{
if (tank.transform.position.x == positionX && tank.transform.position.y == positionY)
{
check = false;
}
else
{
check = true;
}
}
} while (check != true);
Instantiate(tank, new Vector2(positionX, positionY), transform.rotation);
}
}```
Firstly the problem that is doing you in:
By default bool variables. like check, are false. The while loops when check is false. The only way for check to be set to true is thru the forloop if the generated coordinates don't match any tank positions. The problem with that is that if there are no tanks in the scene the forloop is never even started meaning that there is no way for check to become true, ergo your while loop keeps looping and hangs up your editor.
A quick solution would be to check the length of found tanks array and if it is zero set check to true.
if (tanks.Length == 0)
{
check = true;
}
Sidenotes:
There is name ambiguity between the tank in the forloop and the tank in the prefab. Its good practice to avoid that.
It is extremely hard to match two float values with == due to rounding. They might be extremely close, but are still different.
With your method tanks will still overlap. I would recommend to check if a position is truly free, by using Physics2D.OverlapBox or Physics2D.OverlapCircle
If a lot of tanks spawn there might not be any valid positions. You should think of a way to timeout or impose some other limit, else you'll get softlocked in the while loop again.

Adding a delay in my code, not working. C++

Trying to make simon says game as my semester project, problem is I cant add a delay between the colors when they change,
i.e i want to add a delay so that when one box color changes, then after about 3~4 seconds the next box color changes, but the problem is when I put the Sleep() in my for loop, the system pauses for the amount given as a whole, then displays all the colors changed at the same time not one by one....
Any help, here is the function that i call when the game's start button is clicked. How to fix it ?
void flash()
{
srand(time(NULL));
int x;
for (int i = 5; i > 0;i--)
{
x = rand() % 4;
if (x == 0)
{
button1->BackColor = System::Drawing::Color::Blue;
}
else if (x == 1)
{
button2->BackColor = System::Drawing::Color::Blue;
}
else if (x == 2)
{
button3->BackColor = System::Drawing::Color::Blue;
}
else if (x == 3)
{
button4->BackColor = System::Drawing::Color::Blue;
}
Sleep(500);
}
}
P.s I have tried to put the sleep in the if statements but that doesn't work either, Any help please ?
As your code is single-treaded and you are updating the colors of the buttons in a loop, there is (currently) no chance for the application's standard drawing routines to kick in, until the loop is finished. If you do want a redraw while being in the loop, you have to manually issue it by (e.g.):
button1->Invalidate();
button1->Update();
Please be aware that, if you stay in the loop for too long, windows does recognize that your application is not responding to windows messages and renders it "unresponsive" (window fading to half white). To circumvent this, you can use the Timer class from System::Windows::Forms to implement the delay behaviour.

Allegro 5 detects long key press as several key presses

In the code block below I am trying to move a rectangle once for every key-press but the rectangle moves as long as I hold down a key.
ALLEGRO_EVENT ev;
while(!done)
{
al_wait_for_event(event_queue, &ev);
if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_UP:
pos_y -= 10;
break;
case ALLEGRO_KEY_DOWN:
pos_y += 10;
break;
case ALLEGRO_KEY_RIGHT:
pos_x += 10;
break;
case ALLEGRO_KEY_LEFT:
pos_x -= 10;
break;
}
}
else if(ev.type == ALLEGRO_EVENT_KEY_UP)
{
if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
done = true;
}
al_draw_filled_rectangle(pos_x, pos_y, pos_x + 30, pos_y + 30, al_map_rgb(255,0,255));
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
}
Also I noticed that al_wait_for_event is not waiting for a new event in case of holding down a key but is in fact making the event of type ALLEGRO_EVENT_KEY_CHAR . Although this should not pose any problem , I wanted to know a bit more about it.
Also, the above code is taken from a tutorial. It worked fine over there.
To make sure your app doesn't apply the key press more than once per Key_Down event define a Boolean initialized to false. Place everything in your Key_Down events in an If statement triggering only if Boolean == false and in its block immediately set Boolean = true followed by the things you want the event to do only once per event.
Then, in the corresponding Key_Up event set
Boolean = false and you should be golden.
I haven't tested this, but it should work, and it serves towards compating your app to any client computer, no matter if they have funky key press settings on their device.

Cannot get OpenAL to play sound

I've searched the net, I've searched here. I've found code that I could compile and it works fine, but for some reason my code won't produce any sound. I'm porting an old game to the PC (Windows,) and I'm trying to make it as authentic as possible, so I'm wanting to use generated wave forms. I've pretty much copied and pasted the working code (only adding in multiple voices,) and it still won't work (even thought the exact same code for a single voice works fine.) I know I'm missing something obvious, but I just cannot figure out what. Any help would be appreciated thank you.
First some notes... I was looking for something that would allow me to use the original methodology. The original system used paired bytes for music (sound effects - only 2 - were handled in code.) A time byte that counted down every time the routine was called, and a note byte that was played until time reached zero. this was done by patching into the interrupt vector, windows doesn't allow that, so I set up a timer that routing that accomplished the same thing. The timer kicks in, updates the display, and then runs the music sequence. I set this up with a defined time so that I only have one place to adjust the timing at (to get it as close as possible to the original sequence. The music is a generated wave form (and I've double checked the math, and even examined the generated data in debug mode,) and it looks good. The sequence looks good, but doesn't actually produce sound. I tried SDL2 first, and it's method of only playing 1 sound doesn't work for me, also, unless I make the sample duration extremely short (and the sound produced this way is awful,) I can't match the timing (it plays the entire sample through it's own interrupt without letting me make adjustments.) Also, blending the 3 voices together (when they all run with different timings,) is a mess. Most of the other engines I examined work in much the same way, they want to use their own callback interrupt and won't allow me to tweak it appropriately. This is why I started working with OpenAL. It allows multiple voices (sources,) and allows me to set the timings myself. On advice from several forums, I set it up so that the sample lengths are all multiples of full cycles.
Anyway, here's the code.
int main(int argc, char* argv[])
{
FreeConsole(); //Get rid of the DOS console, don't need it
if (InitLog() < 0) return -1; //Start logging
UINT_PTR tim = NULL;
SDL_Event event;
InitVideo(false); //Set to window for now, will put options in later
curmusic = 5;
InitAudio();
SetTimer(NULL,tim,_FREQ_,TimerProc);
SDL_PollEvent(&event);
while (event.type != SDL_KEYDOWN) SDL_PollEvent(&event);
SDL_Quit();
return 0;
}
void CALLBACK TimerProc(HWND hWind, UINT Msg, UINT_PTR idEvent, DWORD dwTime)
{
RenderOutput();
PlayMusic();
//UpdateTimer();
//RotateGate();
return;
}
void InitAudio(void)
{
ALCdevice *dev;
ALCcontext *cxt;
Log("Initializing OpenAL Audio\r\n");
dev = alcOpenDevice(NULL);
if (!dev) {
Log("Failed to open an audio device\r\n");
exit(-1);
}
cxt = alcCreateContext(dev, NULL);
alcMakeContextCurrent(cxt);
if(!cxt) {
Log("Failed to create audio context\r\n");
exit(-1);
}
alGenBuffers(4,Buffer);
if (alGetError() != AL_NO_ERROR) {
Log("Error during buffer creation\r\n");
exit(-1);
}
alGenSources(4, Source);
if (alGetError() != AL_NO_ERROR) {
Log("Error during source creation\r\n");
exit(-1);
}
return;
}
void PlayMusic()
{
static int oldsong, ofset, mtime[4];
double freq;
ALuint srate = 44100;
ALuint voice, i, note, len, hold;
short buf[4][_BUFFSIZE_];
bool test[4] = {false, false, false, false};
if (curmusic != oldsong) {
oldsong = (int)curmusic;
if (curmusic > 0)
ofset = moffset[(curmusic - 1)];
for (voice = 1; voice < 4; voice++)
alSourceStop(Source[voice]);
mtime[voice] = 0;
return;
}
if (curmusic == 0) return;
//Only 3 voices for music, but have
for (voice = 0; voice < 3; voice ++) { // 4 set asside for eventual sound effects
if (mtime[voice] == 0) { //is note finished
alSourceStop(Source[voice]); //It is, so stop the channel (source)
mtime[voice] = music[ofset++]; //Get the next duration
if (mtime[voice] == 0) {oldsong = 0; return;} //zero marks end, so restart
note = music[ofset++]; //Get the next note
if (note > 127) { //Old HW data was designed for could only
if (note == 255) note = 127; //use values 128 - 255 (255 = 127)
freq = (15980 / (voice + (int)(voice / 3))) / (256 - note); //freq of note
len = (ALuint)(srate / freq); //A single cycle of that freq.
hold = len;
while (len < (srate / (1000 / _FREQ_))) len += hold; //Multiply till 1 interrup cycle
while (len > _BUFFSIZE_) len -= hold; //Don't overload buffer
if (len == 0) len = _BUFFSIZE_; //Just to be safe
for (i = 0; i < len; i++) //calculate sine wave and put in buffer
buf[voice][i] = (short)((32760 * sin((2 * M_PI * i * freq) / srate)));
alBufferData(Buffer[voice], AL_FORMAT_MONO16, buf[voice], len, srate);
alSourcei(openAL.Source[i], AL_LOOPING, AL_TRUE);
alSourcei(Source[i], AL_BUFFER, Buffer[i]);
alSourcePlay(Source[voice]);
}
} else --mtime[voice];
}
}
Well, it turns out there were 3 problems with my code. First, you have to link the built wave buffer to the AL generated buffer "before" you link the buffer to the source:
alBufferData(buffer,AL_FORMAT_MONO16,&wave_sample,sample_lenght * sizeof(short),frequency);
alSourcei(source,AL_BUFFER,buffer);
Also in the above example, I multiplied the sample_length by how many bytes are in each sample (in this case "sizeof(short)".
The final problem was that you need to un-link a buffer from the source before you change the buffer data
alSourcei(source,AL_BUFFER,NULL);
The music would play, but not correctly until I added that line to the note change code.

X11/Xlib: Window always on top

A window should stay on top of all other windows. Is this somehow possible with plain x11/xlib? Googling for "Always on top" and "x11" / "xlib" didn't return anything useful.
I'd avoid toolkits like GTK+, if somehow possible.
I'm using Ubuntu with gnome desktop. In the window menu, there's an option "Always On Top". Is this provided by the X server or the window manager? If the second is the case, is there a general function that can be called for nearly any wm? Or how to do this in an "X11-generic" way?
Edit: I implemented fizzer's answer, now having following code:
XSelectInput(this->display, this->window,
ButtonPressMask |
StructureNotifyMask |
ExposureMask |
KeyPressMask |
PropertyChangeMask |
VisibilityChangeMask );
// ...
// In a loop:
if (XPending(this->display) >= 0)
{
XNextEvent(this->display, &ev);
switch(ev.type) {
// ...
case VisibilityNotify:
XRaiseWindow(this->display, this->window);
XFlush(this->display);
break;
// ...
}
}
But the eventhandling and raising nearly never gets executed even my mask is correct?!
#define _NET_WM_STATE_REMOVE 0 // remove/unset property
#define _NET_WM_STATE_ADD 1 // add/set property
#define _NET_WM_STATE_TOGGLE 2 // toggle property
Bool MakeAlwaysOnTop(Display* display, Window root, Window mywin)
{
Atom wmStateAbove = XInternAtom( display, "_NET_WM_STATE_ABOVE", 1 );
if( wmStateAbove != None ) {
printf( "_NET_WM_STATE_ABOVE has atom of %ld\n", (long)wmStateAbove );
} else {
printf( "ERROR: cannot find atom for _NET_WM_STATE_ABOVE !\n" );
return False;
}
Atom wmNetWmState = XInternAtom( display, "_NET_WM_STATE", 1 );
if( wmNetWmState != None ) {
printf( "_NET_WM_STATE has atom of %ld\n", (long)wmNetWmState );
} else {
printf( "ERROR: cannot find atom for _NET_WM_STATE !\n" );
return False;
}
// set window always on top hint
if( wmStateAbove != None )
{
XClientMessageEvent xclient;
memset( &xclient, 0, sizeof (xclient) );
//
//window = the respective client window
//message_type = _NET_WM_STATE
//format = 32
//data.l[0] = the action, as listed below
//data.l[1] = first property to alter
//data.l[2] = second property to alter
//data.l[3] = source indication (0-unk,1-normal app,2-pager)
//other data.l[] elements = 0
//
xclient.type = ClientMessage;
xclient.window = mywin; // GDK_WINDOW_XID(window);
xclient.message_type = wmNetWmState; //gdk_x11_get_xatom_by_name_for_display( display, "_NET_WM_STATE" );
xclient.format = 32;
xclient.data.l[0] = _NET_WM_STATE_ADD; // add ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE;
xclient.data.l[1] = wmStateAbove; //gdk_x11_atom_to_xatom_for_display (display, state1);
xclient.data.l[2] = 0; //gdk_x11_atom_to_xatom_for_display (display, state2);
xclient.data.l[3] = 0;
xclient.data.l[4] = 0;
//gdk_wmspec_change_state( FALSE, window,
// gdk_atom_intern_static_string ("_NET_WM_STATE_BELOW"),
// GDK_NONE );
XSendEvent( display,
//mywin - wrong, not app window, send to root window!
root, // <-- DefaultRootWindow( display )
False,
SubstructureRedirectMask | SubstructureNotifyMask,
(XEvent *)&xclient );
XFlush(display);
return True;
}
return False;
}
You don't want to use XRaiseWindow() to try to stay on top. Some window managers will ignore it entirely. For those that don't, consider what happens if more than one app tries to do this. Boom! That's why the window manager is in charge of stacking windows, not the app.
The way you do this is to use the protocols defined in the Extended Window Manager Hints (EWMH), see: http://www.freedesktop.org/wiki/Specifications/wm-spec
Specifically here you want _NET_WM_STATE_ABOVE which is how the "Always on Top" menu item works.
If you aren't using a toolkit you'll want to get used to scavenging in toolkit source code to figure out how to do things. In this case you could look at the function gdk_window_set_keep_above() in GTK+'s X11 backend. That will show how to use the _NET_WM_STATE_ABOVE hint.
I wrote something like this in Xlib many years ago. It's a few lines of code. When your window is partially obscured you get a VisibilityNotify event, then call XRaiseWindow. Watch out for the case where two of your 'always on top' windows overlap.
Use Actual Title Buttons (http://www.actualtools.com/titlebuttons/) for example. It allows to stay any windows always on top , roll up, make transparency and etc..

Resources