I'm using a combination of SDL and OpenGL in a sort of crash course project to teach myself how this all works. I'm really only interested in OpenGL as a way to use acceleration in 2D games so I just need this to work in a 2D plane.
I have been having a lot of problems today with my current issue, I would like an object to point towards the mouse while the mouse button is clicked and then of course stay pointing in that direction after the mouse is lifted.
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: down开发者_Python百科Up = 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 Object::Move call which also handles 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 the object turns and faces down to the bottom left but then no longer changes direction. I'd really appreciate any help I could get here. I'm guessing there might be an issue here with state versus polled events but from all the tutorials that I've been through I was pretty sure I had fixed that. I've just hit a wall and I need some advice!
I'm assuming that you want the object to keep pointing at the mouse's position while the mouse button is held. To fix this, you will have to update the mouse position every time the mouse is moved.
Add some code similar to this:
if( event.type == SDL_MOUSEMOVE ) {
// update the mouse position here using event.???.x / y
}
Note that I haven't got an SDL reference here, so I can't give you the exact members, but that should help.
NB: I would also guess that there would be problems with your button handling code. You have an if statement that checks for one value of event.type
, but then inside its body you have a switch statement with two values. Only one of these values will ever be executed - you should probably think about just using 2 separate if statements for the button down / button up events.
精彩评论