我试图让玩家平稳地运动,例如模拟物理重力到速度,但是效果不好。我刚刚按下的方向键会延迟一段时间才能产生效果,然后停止所有奇怪的动作。我绘制了一个红色的矩形,并尝试像飞船的月球着陆器那样进行控制,但是无法正常工作。
有人可以帮我吗?
#include <SDL.h>
#include <stdio.h>
// for random number
#include <stdlib.h>
#include <SDL_image.h>
#include <ctime>
SDL_Surface *screen = NULL;
SDL_Surface *playership = NULL;
//SDL_Renderer *renderer = NULL;
SDL_Window *window = NULL;
SDL_Event occur;
SDL_Rect PlayerShip;
//Definition Color PlayerShip
Uint32 red;
// X and Y velocity of Ball variables
float xVelShip, yVelShip;
// dx dy momentum acel decel velocity player
float dx, dy;
int GetRandomNumber(int high, int low)
{
return rand() % high + low;
}
void Load_Game()
{
/*Initialize SDL*/
SDL_Init(SDL_INIT_EVERYTHING);
//SDL_Window* window = nullptr;
//Create window
window = SDL_CreateWindow( "SDL_lunarlander", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN);
screen = SDL_GetWindowSurface( window );
//Player setup
PlayerShip.x = GetRandomNumber(500,200);
PlayerShip.y = 200;
PlayerShip.w = 10;
PlayerShip.h = 30;
dx = 0.0f;
dy = 0.0f;
//Color Player
red = SDL_MapRGB(screen->format, 255, 0, 0);
//ramdon number to movemment Ball
srand((int)time(0));
}
void Draw_Level()
{
SDL_FillRect(screen, NULL, 0);
SDL_FillRect(screen, &PlayerShip, red);
SDL_UpdateWindowSurface( window );
}
void Logic()
{
dy += 0.15f;
if ( PlayerShip.y < 558)
{
PlayerShip.y += dy*0.05f;
}
if ( PlayerShip.x < 800)
{
PlayerShip.x = dx;
}
// SDL 2.0 USES
//const Uint8 *keystates = SDL_GetKeyboardState(NULL);
//if (keystates[SDL_SCANCODE_W])
const Uint8 *keystates = SDL_GetKeyboardState(NULL);
if (keystates[SDL_SCANCODE_UP])
{
dy -= 0.65f;
}
if (keystates[SDL_SCANCODE_DOWN])
{
dy += 0.25f;
}
if (keystates[SDL_SCANCODE_RIGHT])
{
dx += 0.2f;
}
if (keystates[SDL_SCANCODE_LEFT])
{
dx -= 0.2f;
}
}
int main( int argc, char* args[] )
{
printf("FPS:%d", SDL_GetTicks());
Load_Game();
bool running = true;
// CAP FPS to 60 may be not working
const int FPS=60;
Uint32 start;
printf("FPS:%d", SDL_GetTicks());
while(running == true)
{
start = SDL_GetTicks();
SDL_PollEvent(&occur);
if (occur.type == SDL_QUIT)
{
running = false;
}
Logic();
Draw_Level();
// CAP FPS to 60 Maybe not working
if (1000/FPS > SDL_GetTicks() - start)
{
SDL_Delay( 1000/FPS - (SDL_GetTicks() - start));
}
}
SDL_FreeSurface(screen);
SDL_DestroyWindow( window );
SDL_Quit();
return 0;
}```