2011-10-01 194 views
0

我的游戏程序有问题。该程序响应我的键盘输入,但不会移动太远。它只会移动1位。C++ SDL键盘响应

#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代码:

#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 

一切工作正常,除了它的运动。它永远不会移动太远,一旦释放它就会回到原来的位置。

回答

1

每当您拨打player()时,您都将位置设置为(40,40)。你需要将玩家的初始化与玩家的处理分开。

+0

我该怎么做?如何从他的处理中分离他的位置? – user974327

+1

@ user974327:在C++中存储状态的习惯方法是在* objects *中。执行处理的惯用方式是通过*成员函数*。有关该主题的文献很多。 – molbdnilo