I am trying to code a 2D shooter using SDL. My computer system is a G4 iBook with Mac OS X 1.4.8 installed. I have encountered a bug that is really messing with my sanity.
This is the code for my main loop:
#include <iostream>
#include "SDL/SDL.h"
#include "player.h"
#include "video.h"
#include "sprite.h"
#include "timer.h"
#include "spritefactory.h"
int main(int argc, char *argv[])
{
Video::init();
Timer::init();
SpriteFactory::init();
SpriteFactory::load_sdata("data/player.sdata");
Player player;
player.fetch_sprite_set("player");
bool quit = false;
SDL_Event event;
// SDL_Rect mysterious_rectangle;
while(quit != true) {
player.update();
player.blit_sprite(0);
Video::flip();
// Timer::start();
while(SDL_PollEvent(&event)) {
player.parse_input(event);
if (event.type == SDL_QUIT)
quit = true;
}
Timer::wait();
}
Video::quit();
Timer::quit();
SpriteFactory::quit();
return 0;
}
The interesting part is Player::parse_input()
void Player::parse_input(SDL_Event &event)
{
SDL_Rect velocity = get_velocity();
if(event.type == SDL_KEYDOWN) {
switch(event.key.keysym.sym) {
case SDLK_UP: velocity.y += -1;
break;
case SDLK_DOWN: velocity.y += 1;
break;
case SDLK_LEFT: velocity.x += -1;
break;
case SDLK_RIGHT: velocity.x += 1;
break;
default:
break;
}
}
else if(event.type == SDL_KEYUP) {
switch(event.key.keysym.sym) {
case SDLK_UP: velocity.y -= -1;
break;
case SDLK_DOWN: velocity.y -= 1;
break;
case SDLK_LEFT: velocity.x -= -1;
break;
case SDLK_RIGHT: velocity.x -= 1;
break;
default: break;
}
}
std::cout << velocity.x << " " << velocity.y << std::endl;
set_velocity(velocity);
}
If I launch the program my player sprite will be displayed and when I press the arrow buttons it will move around on the screen. The standard output (printed from Player::parese_input()) reads something like:
0 0
0 0
1 0
1 1
0 1
0 0
1 0
0 0
0 1
0 0
1 0
0 0
0 1
0 0
-1 0
0 0
0 -1
0 0
1 0
0 0
0 1
All according to the expected response. But now to the interesting part. If I uncomment the SDL_Rect mysterious_rectangle part from my main.cc, my program breaks down. The ship is not displayed on my screen and standard output now reads:
-16400 0
-16400 0
-16399 0
-16400 0
-16401 0
-16400 0
-16400 -1
-16400 0
-16400 -1
-16400 0
-16401 0
-16400 0
-16400 1
-16400 0
-16401 0
-16400 0
-16400 -1
-16400 0
-16399 0
-16399 1
-16400 1
-16400 0
As far as I know, SDL_Rect is only a struct with four integers, how can it affect my program in such a way? I dont use mysterious_rectangle anywhere else in the program, the compiler even complains
main.cc: In function 'int SDL_main(int, char**)':
main.cc:21: warning: unused variable 'mysterious_rectangle'
it should have no effect on my program. Either I am missing something very basic and then I apologize that I am not posting in the beginners forum or SDL is doing something fishy (as the warning is mentioning SDL_main).
Would be very happy if someone could find an answer to this behavior.
Thank you.
[Edited by - psa on October 8, 2006 5:22:57 AM]