Can't get my object to point to mouse
I am using a combination of SDL and OpenGL in some course project to teach myself how it all works. I'm really interested in OpenGL as a way to accelerate in 2D games, so I just need this to work in a 2D plane.
I had a lot of problems today with my current problem, I would like the object to point to the mouse when the mouse button is pressed, and then of course continue to point in that direction after the mouse is raised.
void Square::handle_input() {
//If a key was pressed
if( event.type == SDL_KEYDOWN ) {
//Adjust the velocity
switch( event.key.keysym.sym ) {
case SDLK_UP: upUp = false; yVel = -1; break;
case SDLK_DOWN: downUp = false; yVel = 1; break;
case SDLK_LEFT: leftUp = false; xVel = -1; break;
case SDLK_RIGHT: rightUp = false; xVel = 1; break;
case SDLK_w: wUp = false; sAng = 1; break;
case SDLK_s: sUp = false; sAng = -1; break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP ) {
//Adjust the velocity
switch( event.key.keysym.sym ) {
case SDLK_UP: upUp = true; yVel = 0; break;
case SDLK_DOWN: downUp = true; yVel = 0; break;
case SDLK_LEFT: leftUp = true; xVel = 0; break;
case SDLK_RIGHT: rightUp = true; xVel = 0; break;
case SDLK_w: wUp = true; sAng = 0; break;
case SDLK_s: sUp = true; sAng = 0; break;
}
}
//If a mouse button was pressed
if( event.type == SDL_MOUSEBUTTONDOWN ) {
switch ( event.type ) {
case SDL_MOUSEBUTTONDOWN: mouseUp = false; mousex == event.button.x; mousey == event.button.y; break;
case SDL_MOUSEBUTTONUP: mouseUp = true; break;
}
}
}
And then this is called at the end of my call to Object :: Move, which also handles the x and y translation
if (!mouseUp) { xVect = mousex - x; yVect = mousey - y; radAng = atan2 ( mousey - y, mousex - x ); sAng = radAng * 180 / 3.1415926l; }
Right now, when I click on an object, it rotates and drops down to the bottom left, but then no longer changes direction. I am very grateful for any help I could get here. I am guessing there might be an issue with government or poll events here, but from all the tutorials I went through, I was confident that I had fixed this. I just hit the wall and I need advice!
a source to share
I am assuming that you want the object to keep pointing to the mouse position as long as the mouse button is held down. To fix this, you will have to update the mouse position every time the mouse is moved.
Add code similar to this:
if( event.type == SDL_MOUSEMOVE ) {
// update the mouse position here using event.???.x / y
}
Note that I have no SDL reference, so I cannot give you the exact members, but that should help.
NB: I would also guess there will be problems with the button handling code. You have an if statement that tests one value event.type
, but then inside its body you have a switch statement with two values. Only one of these values will ever get executed - you should probably only think about using only two separate if statements for button / button click events.
a source to share