开发者

C++ SDL keyboard response

I have a problem with my game program. The program responds to my keyboard input but won't move far. It will only move 1 bit up.

#include <SDL/SDL.h>
#include "Mrn.h"

int main (int argc,char** argv)
{
SDL_Init(SDL_INIT_EVERYTHING);//initialized everything.
SDL_Surface* screen;//allows drawing on screen.
screen=SDL_SetVideoMode(500,500,32,SDL_SWSURFACE);//sets resolution of screen.
bool running = true;
const int FPS = 30;//fps of the game.
Uint32 start;
while(running)//windows running loop.
{
    start = SDL_GetTicks();//timer.
    SDL_Event event;//allows for events to happen.
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_QUIT:
            running = false;//allows exiting.
            break;
        }
    }
    //game logic and rendering.
    player(screen);
    SDL_Flip(screen);
    if(1000/FPS > SDL_GetTicks() - start)
    {
        SDL_Delay(1000/FPS - (SDL_GetTicks() - start));
    }

}
SDL_Quit();
return 0;
}
开发者_运维问答

Player.h code:

#include <SDL/SDL.h>
#ifndef MRN_H_INCLUDED
#define MRN_H_INCLUDED

int player(SDL_Surface* screen)
{
SDL_Surface* Marine;
SDL_Rect first;
first.x = 0;
first.y = 0;
first.w = 42;
first.h = 31;
SDL_Rect position;
position.x = 40;
position.y = 40;
Uint8 *key;
key = SDL_GetKeyState(NULL);

if(key[SDLK_w])
{
    position.y++;
}

Marine = SDL_LoadBMP("Images/Marine.bmp");
SDL_BlitSurface(Marine,&first,screen,&position);
SDL_FreeSurface(Marine);
return 0;
}

#endif // MRN_H_INCLUDED

everything works fine except for its movement. It will never move far and on release it will move back to its original position.


Every time you call player(), you are setting position to (40,40). You need to separate player's initialization from player's processing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜