【发布时间】:2018-01-13 11:55:19
【问题描述】:
我的代码的问题是我正在使用 C++ 中的 SDL 2.0 制作乒乓球游戏。我做了一切,直到创建运动。当玩家桨移动时,它会留下与桨相同颜色的轨迹。我在 YouTube 上观看了一些视频,但是当他们进行移动时,它很好而且清晰,我可以解决这个问题,但我需要在每次玩家移动时重新着色背景,这使得它变得很华丽,如果我按住按钮,我不会根本看不到桨。
#include<iostream>
#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>
#include<windows.h>
#define width 800
#define height 600
using namespace std;
bool run = true;
class Player{
private:
SDL_Window* window = SDL_CreateWindow("Pong!", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_RESIZABLE);
SDL_Surface* Screen = SDL_GetWindowSurface(window);
Uint32 screen_color = SDL_MapRGB(Screen->format, 0, 0, 0);
Uint32 In_game_RGB = SDL_MapRGB(Screen->format, 255, 255, 255);
SDL_Rect Pl;
SDL_Rect AI;
SDL_Rect Ball;
SDL_Rect ClearP;
SDL_Rect ClearAI;
public:
Player(){
//Player parameters
Pl.x = 60;Pl.y = 225;Pl.w = 25;Pl.h = 200;
//AI parameters
AI.x = 720;AI.y = 225;AI.w = 25;AI.h = 200;
//Ball parameters
Ball.x = width/2;Ball.y = height/2+10;Ball.w = 25;Ball.h = 25;
//Recoloring parameters
ClearP.x = 0;ClearP.y = 0; ClearP.w = 375;ClearP.h = height;
ClearAI.x = 425;ClearAI.y = 0;ClearAI.w = 375;ClearAI.h = height;
//Make the screen color black
SDL_FillRect(Screen, NULL, screen_color);
}
void scrUpdate(){
SDL_UpdateWindowSurface(window);
}
void drawPlayer(){
SDL_FillRect(Screen, &Pl, In_game_RGB);
}
void drawComputer(){
SDL_FillRect(Screen, &AI, In_game_RGB);
}
void ball(){
SDL_FillRect(Screen, &Ball, In_game_RGB);
}
void Movement(){
if(GetAsyncKeyState(VK_DOWN)){
Pl.y += 2;
SDL_FillRect(Screen,&ClearP,screen_color);
}
if(GetAsyncKeyState(VK_UP)){
SDL_FillRect(Screen,&ClearP,screen_color);
Pl.y -= 2;
}
}
};
void EventCheck(){
SDL_Event event;
if(SDL_PollEvent(&event)){
if(event.type == SDL_QUIT){
run = false;
}
}
}
int main( int argc, char *argv[] )
{
SDL_Init(SDL_INIT_EVERYTHING);
Player Play;
//Player Computer();
while(run){
Play.scrUpdate();
Play.drawPlayer();
Play.drawComputer();
Play.ball();
Play.Movement();
EventCheck();
}
SDL_Quit();
return EXIT_SUCCESS;
}
【问题讨论】:
-
您需要清除视口(例如
SDL_RenderClear),但我想您已经想到了。如果你说你有闪烁而其他人没有——那么很可能你正在做他们没有做的事情;由于没有显示代码,因此理论上只有您可以知道那是什么。 -
其他人唯一不同的是他们使用的是较旧的 sdl 版本,但我从未尝试过 SDL_RenderClear 我会尝试一下。谢谢
-
我还添加了我正在使用的代码,您可以自己尝试一下,看看是否有相同的结果。只需向向上箭头键发送垃圾邮件,这样您就可以真正看到玩家的划桨。不要拿着它
-
@PlamenTsanev 好吧,你不使用 SDL 渲染器,所以没有 renderclear 适合你。不过,您正在使用 FillRect 做类似的事情。闪烁是因为您绘制矩形,然后如果发生事件将其擦除,然后将其显示在屏幕上 - 之后,您什么也不显示(现在绘制的内容已擦除),并且如果未按住按钮,只会在下一帧绘制。你应该改变事情的顺序——首先检查事件和擦除/移动(擦除阶段可以/应该被删除,但这不是重点),然后绘制。