The problem with my code is that I am making a pong game in SDL 2.0 in c++. I did everything until creating the movement. When the player paddle moves, it leaves behind a trail in the same color as the paddle. I watched some videos on YouTube, but when they do the movement it's nice and clear and for me to fix this but I need to recolor the background every time the player moves, which makes it being all flashy and if I hold the button I don't see the paddle at all.
#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;
}
It would help to show some code or an example of what you have been doing, or a link to one of the videos you have been watching:
Youtube tutorial
but I suggest taking a look at:
screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE); and SDL_Flip(screen) as those have to do with screen buffering and drawing.
Another possibilty is that you are running an outdated version of SDL, or an incompatible one with your current system.
To be able to give a more complete and proper answer, I'd highly suggest adding more information about your code, screenshots of results and your version of SDL and operating system.
Also, you said it was flashy when you hold the paddle. I think it must be that you are performing your logic to move the paddle and you redraw the paddle once it's still. If you are redrawing the entire screen constantly, consider double buffering.
Related
To keep it short, I have this class Display_Frame. Within this Display_Frame, there are 2 rectangles. The first being its own rectangle, and the second being its internal rectangle. The first rectangle is for its positioning and dimensions on a screen, and the second (internal rectangle) is for information within that first rectangle. If the internal rectangle is bigger than the first rectangle, I initiate a scrollbar on the side to scroll for the information. This is where my problem is discovered. If I use this approach for every object on my screen, ie, the main display is its own Display_Frame, then any other object on the screen can also fit within another Display_Frame but is fitted in the screen via the main screens one. When I then scroll, How can I make sure that only the farthest branch of Display_Frame's is scrolled, and not any others.
For example, lets say I have a textbox that fits inside its own Display_Frame. Its own Display_Frame is also embedded within the main screens Display_Frame too. Now lets say I want to scroll in the textbox but only if the mouse is within it. That's easy enough to detect, however how can I make it so that when I do scroll inside the textbox, the main screens Display_Frame doesn't scroll, only the textbox's Display_Frame 's internal rect is moved instead.
In general terms for this, how can I efficiently detect and restrict my Display_Frame's to only scroll if I have scrolled on the farthest down branch of Display_Frame's?
Here is some code displaying my issue:
#include <SDL2/SDL.h>
class Display_Frame
{
public:
SDL_Rect m_Display_Frame_Rect;
SDL_Rect m_Internal_Rect;
void Handle_Events(SDL_Point mousePos, bool scrolledDown, bool scrolledUp);
};
void Display_Frame::Handle_Events(SDL_Point mousePos, bool scrolledDown, bool scrolledUp)
{
if (SDL_PointInRect(&mousePos, &m_Display_Frame_Rect))
{
if (scrolledDown){
m_Display_Frame_Rect.y += 20;
}
if (scrolledUp){
m_Display_Frame_Rect.y -= 20;
}
}
}
int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Rect display = {0,0,1278,718};
SDL_Window* window = SDL_CreateWindow("Test", 0, 30, display.w+2, display.h+2, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE );
SDL_Renderer* renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );
SDL_Rect testRect = {100, 100, 100, 100};
SDL_Point mousePos = {0,0};
SDL_Event event;
bool running = true;
bool scrolledUp = false, scrolledDown = false;
Display_Frame mainDisplay;
mainDisplay.m_Display_Frame_Rect = display;
mainDisplay.m_Internal_Rect = display;
Display_Frame smallDisplay;
smallDisplay.m_Display_Frame_Rect = testRect;
smallDisplay.m_Internal_Rect = testRect;
while (running)
{
scrolledDown = false;
scrolledUp = false;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT){
running = false;
break;
}
if (event.type == SDL_MOUSEMOTION)
{
mousePos = {event.motion.x, event.motion.y};
}
if (event.type == SDL_MOUSEWHEEL){
if (event.wheel.y > 0){ ///Scrolling up here
scrolledUp = true;
}
if (event.wheel.y < 0){ ///Scrolling down here
scrolledDown = true;
}
}
}
SDL_SetRenderDrawColor(renderer, 255,255,255,255);
SDL_RenderClear(renderer);
mainDisplay.Handle_Events(mousePos, scrolledDown, scrolledUp);
smallDisplay.Handle_Events(mousePos, scrolledDown, scrolledUp);
SDL_SetRenderDrawColor(renderer, 0,0,0,255);
SDL_RenderDrawRect(renderer, &mainDisplay.m_Display_Frame_Rect);
SDL_RenderDrawRect(renderer, &smallDisplay.m_Display_Frame_Rect);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
In my project, I have a decreasing timer progress bar PNG image on display. This image and its background can be found at the below link:
https://s3.eksiup.com/df7dd38f781.png
My goal is to make the bar decrease starting from the upper green side to the lower red side. My code for this is the following:
void EntityTimer::OnRender(SDL_Renderer *ren)
{
SDL_Rect currRect,dstRect;
double rem=0.0;
memcpy(&currRect,&origRect,sizeof (SDL_Rect));
memcpy(&dstRect,&origRect,sizeof (SDL_Rect));
if (timerObjPtr->remainingDuration>timerObjPtr->durationInMilisec)
timerObjPtr->durationInMilisec=timerObjPtr->remainingDuration;
rem=((double)timerObjPtr->remainingDuration/timerObjPtr->durationInMilisec);
currRect.h=(origRect.h)*rem;
currRect.h = currRect.h;
dstRect.x=0;
dstRect.y=0;
dstRect.h=currRect.h;
SDL_RenderCopy(ren,timerTexture,&dstRect,&currRect);
}
Since this image is static, I tried to do it by manipulating this texture's height parameter with "currRect.h=(origRect.h)*rem;" line. But this makes the progress bar to decrease from the red side to the green side (the opposite of what I want).
I tried to correct it but made it worse by mirroring the PNG image on the progress bar area and decreasing it from bottom to top again.
Any help is appreciated so that the bar decreases from top (green) to bottom (red).
Well that's kinda expected since you're drawing from the same point (x = 0, y = 0) but using a smaller size. You need to update the destine y position:
dstRect.y = origRect.h - origRect.h * rem;
EDIT: It was the other way around
dstRect.y = origRect.h * rem
(assuming rem goes from 0 to 1)
Here is an example of what you want, you can use this image to test https://i.imgur.com/faKKShU.png
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <thread>
#define HEIGHT 600
#define WIDTH 800
using namespace std;
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow("Red", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
SDL_Renderer *renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
bool quit = false;
SDL_Event event;
SDL_Texture *red_part = IMG_LoadTexture(renderer, "red_image.png");
float multiplier = 0;
while (!quit) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
quit = true;
}
}
int y_pos = HEIGHT * multiplier;
SDL_RenderClear(renderer);
SDL_Rect copy_rect{0, y_pos, 800, 600};
SDL_RenderCopy(renderer, red_part, nullptr, ©_rect);
SDL_RenderPresent(renderer);
multiplier += 0.01;
if (multiplier >= 1.)
multiplier = 1.;
std::this_thread::sleep_for(std::chrono::milliseconds{33});
}
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
return 0;
}
So I'm starting SDL2 and ran through a few tutorials and decided that I would try to make a simple game and a clone of Pong seemed like the simplest. But I can't seem to be able to make the right hand side paddle draw on the window. At the moment I'm using SDL_FillRenderRect, one for each paddle but that just seems to make the left hand side one appear and not the right hand side. Here's my current code:
#include <iostream>
#include "Pong.h"
#include "Paddle.h"
//Screen size
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
bool quit = false;//Has user quit?
Paddle paddleLeft;
Paddle paddleRight;
int Pong::setup(){
//Initilize SDL
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("Pong",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN);
if (window == nullptr){
std::cout<<"SDL_CreateWindow error: "<<SDL_GetError()<<std::endl;
SDL_Quit();
return -1;
}
SDL_ShowCursor(0);
renderer = SDL_CreateRenderer(window,
-1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
std::cout<<"SDL_CreateRenderer error: "<<SDL_GetError()<<std::endl;
SDL_Quit();
return -1;
}
int wH, wW;
//Setting the paddle to the centre of the left hand side of the screen.
SDL_GetWindowSize(window, &wW, &wH);
paddleLeft.setY((wH / 2) - (paddleLeft.getPaddleHeight() / 2));
paddleRight.setY((wH / 2) - (paddleLeft.getPaddleHeight() / 2));
//Setting the x, y, height and width of the left paddle
leftR.x = 20;
leftR.y = paddleLeft.getY();
leftR.h = paddleLeft.getPaddleWidth();
leftR.w = paddleLeft.getPaddleHeight();
//Setting the x, y, height and width of the right paddle
rightR.x = 620;
rightR.y = paddleLeft.getY();
rightR.h = paddleLeft.getPaddleWidth();
rightR.w = paddleLeft.getPaddleHeight();
return 1;//If setup fails then return -1 otherwise return 1
}
void Pong::updateGame(){
SDL_Event event;
while (SDL_PollEvent(&event)){
if (event.type == SDL_QUIT){
quit = true;
}
if (event.type == SDL_KEYDOWN){
switch (event.key.keysym.sym){
case SDLK_w: paddleLeft.setY(paddleLeft.getY() - paddleLeft.getSpeed()); break;
case SDLK_s: paddleLeft.setY(paddleLeft.getY() + paddleLeft.getSpeed()); break;
}
}
}
}
void Pong::render(){
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
leftR.x = paddleLeft.getX();
leftR.y = paddleLeft.getY();
rightR.x = paddleRight.getX();
rightR.y = paddleRight.getY();
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &leftR);
SDL_RenderFillRect(renderer, &rightR);
SDL_RenderPresent(renderer);
}
void Pong::cleanup(){
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void Pong::run(){
while (!quit){
updateGame();
render();
}
cleanup();
}
Could someone please point me in the correct direction for drawing the right paddle? I would also appreciate it if there are anyother errors in my code or ways to make it more efficent and what not if that could also be pointed out. Thanks in advance.
Read this closely:
rightR.x = 620;
rightR.y = paddleLeft.getY();
rightR.h = paddleLeft.getPaddleWidth();
rightR.w = paddleLeft.getPaddleHeight();
right and left mixed up due to copy-paste programming. I'm not saying it's bad, I do it too to reduce harm on my hands. You should just check things like this twice.
Also, in your case, you should start using OOP concepts. Don't perform everything in non-member functions, make member functions that perform on instances instead. I don't know where the values of getY, getPaddleWidth and getPaddleHeight come from, but it's clear to me that there shouldn't be anything other than SDL_Rect holding them.
I even think that SDL is a waste of time and I can't remember what's C++ about it. It's pure C and you're not going to learn anything useful. SFML is far better choice.
I am trying to create a SDL window which keeps its aspect ratio when resize event happens. If user widens the window, the height is increased and vice versa. I catch the SDL_WINDOWEVENT_RESIZED event, calculate new width or height which maintains the aspect ratio and then call SDL_SetWindowSize() with calculated values.
The problem is that calling the SDL_SetWindowSize() function inside the event polling loop does nothing on the screen. SDL does update the window size variables (calling SDL_GetWindowSize() in my main loop returns the updated window dimensions). However, the actual window is not updated.
The only way I can get this to work is to call constantly SDL_SetWindowSize() in the main loop, but I think that is the wrong way of doing things. The code below illustrates my problem. Is there a better and cleaner way to get this to work?
I am using SDL 2.0.3 and 64-bit Ubuntu Linux with GNOME desktop.
#include <SDL2/SDL.h>
static const float ASPECT_RATIO = 16.f/9.f;
SDL_Window* window;
SDL_Renderer* renderer;
uint32_t windowID;
SDL_Rect screen;
bool done = false;
bool resizeDone = false;
void handle_events()
{
SDL_Event e;
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_WINDOWEVENT:
if(e.window.windowID == windowID) {
switch(e.window.event) {
case SDL_WINDOWEVENT_RESIZED: {
int width = e.window.data1;
int height = e.window.data2;
float aspectRatio = (float)width/(float)height;
if(aspectRatio != ASPECT_RATIO) {
if(aspectRatio > ASPECT_RATIO) {
height = (1.f / ASPECT_RATIO) * width;
}
else {
width = ASPECT_RATIO * height;
}
printf("Setting window size to %d, %d, aspect ratio: %f\n",
width, height, (float)width/(float)height);
}
screen.w = width;
screen.h = height;
SDL_SetWindowSize(window, width, height); // <-- does not work
resizeDone = true;
break;
}
}
}
break;
case SDL_QUIT:
done = true;
break;
default:
break;
}
}
}
void run() {
while(!done) {
//SDL_SetWindowSize(window, screen.w, screen.h); // <-- works
handle_events();
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
if(resizeDone) {
int w, h;
SDL_GetWindowSize(window, &w, &h);
printf("SDL_GetWindowSize: %d, %d\n", w, h);
resizeDone = false;
}
}
}
int main(int, char**) {
SDL_Init(SDL_INIT_VIDEO);
uint32_t window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE;
window = SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, window_flags);
windowID = SDL_GetWindowID(window);
renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
run();
SDL_Quit();
return 0;
}
Some window managers seems to ignore resize requests made while WM itself resizes window (e.g. while mouse button held). On contrary, SDL_GetWindowSize returns cached values, which in that specific case sometimes happens to be wrong.
I see no platform-independent way to achieve that, other than constantly calling SDL_SetWindowSize on each frame, just in case. It could be achieved using platform-specific APIs, though (like SDL_GetWindowSysWMInfo and then using Xlib).
On macOS, I have solved it like this:
cocoa.m:
#import <Cocoa/Cocoa.h>
void SetWindowRatio(void *window) {
NSWindow *win = (__bridge NSWindow*) window;
win.aspectRatio = NSMakeSize( 1280, 720 );
}
main.cpp:
#include <SDL.h>
#include <SDL_syswm.h>
extern "C" void SetWindowRatio(void *window);
// and later..
SDL_SysWMinfo wmInfo;
SDL_VERSION(&wmInfo.version);
SDL_GetWindowWMInfo(sdl.window, &wmInfo);
SetWindowRatio(wmInfo.info.cocoa.window);
Perhaps something similar could be done on Linux, only access different part of wmInfo.info. and call the native function?
(See "Edit 2" below for the solution.)
I need to create SDL surfaces from scratch, instead of loading them from a file. Unfortunately, SDL_BlitSurface() seems to render all colors as black when used with the surface generated through SDL_CreateRGBSurface(). This is my code:
int main(int argc, char** argv)
{
SDL_Surface* screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
SDL_Surface* layer = SDL_CreateRGBSurface(SDL_HWSURFACE, 100, 100,
screen->format->BitsPerPixel,
screen->format->Rmask,
screen->format->Gmask,
screen->format->Bmask,
screen->format->Amask
);
SDL_Rect rect;
rect.x = 0;
rect.y = 0;
rect.w = 100;
rect.h = 100;
Uint32 blue = SDL_MapRGB(screen->format, 0, 0, 255);
SDL_FillRect(layer, &rect, blue);
SDL_BlitSurface(screen, NULL, layer, NULL);
SDL_Flip(screen);
SDL_Delay(3000);
return 0;
}
What I get is a black screen, instead of a 100x100 blue rectangle. What I could find by Googling doesn't seem to help me, as those questions either apply to 8bit surfaces (and setting palettes — my bpp is 32 here) or are left unanswered.
So, I would like to know how should I properly blit a generated surface onto a SDL screen.
Edit: I see it was an error in the parameter ordering. The line in question should read
SDL_BlitSurface(layer, NULL, screen, NULL);
Still, I am having trouble to achieve the same effect in my more complex C++ program. I will post the relevant parts of the code here:
main.cpp:
int main(int argc, char** argv)
{
SDLScreen screen(1024, 700, "Hello, SDL!");
SDL_Event event;
SDLMenu menu;
bool shouldQuit = false;
menu.setBounds(200, 100, 200, 600);
menu.setFontName("NK211.otf");
menu.setFontSize(36);
menu.setEffect(sdlteShadowText);
menu.addItem("New game");
menu.addItem("Load game");
menu.addItem("Save game");
menu.addItem("Exit");
menu.render();
while (!shouldQuit)
{
menu.draw(screen.getSurface());
SDL_Flip(screen.getSurface());
SDL_Delay(10);
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
shouldQuit = true;
}
else if (event.type == SDL_KEYUP)
{
if (event.key.keysym.sym == SDLK_q)
{
shouldQuit = true;
}
}
}
}
}
SDLMenu.cpp:
void
SDLMenu::setSelectionColorRGB(int r, int g, int b)
{
SDL_VideoInfo* info = (SDL_VideoInfo*)SDL_GetVideoInfo();
selectionColor = SDL_MapRGB(info->vfmt, r, g, b);
}
void
SDLMenu::render()
{
SDLText* current = NULL;
SDL_VideoInfo* info = (SDL_VideoInfo*)SDL_GetVideoInfo();
if (!items->empty())
{
current = getItemAt(currentItem);
selectionRect = getItemRect(current);
setSelectionColorRGB(0,0,255);
selectionCanvas = SDL_CreateRGBSurface(SDL_HWSURFACE,
selectionRect->w, selectionRect->h,
info->vfmt->BitsPerPixel,
info->vfmt->Rmask,
info->vfmt->Gmask,
info->vfmt->Bmask,
info->vfmt->Amask);
SDL_FillRect(selectionCanvas, selectionRect, selectionColor);
SDL_SaveBMP(selectionCanvas, "selection.bmp"); // debug
}
for (list<SDLText*>::iterator i = items->begin();
i != items->end(); i++)
{
(*i)->render();
}
}
void
SDLMenu::draw(SDL_Surface* canvas)
{
int currentY = bounds.y;
if (selectionCanvas != NULL)
{
SDL_BlitSurface(selectionCanvas, NULL, canvas, selectionRect);
}
for (list<SDLText*>::iterator i = items->begin();
i != items->end(); i++)
{
(*i)->draw(bounds.x, currentY, canvas);
currentY += fontSize + itemGap;
}
}
SDLScreen.cpp:
SDLScreen::SDLScreen(int w, int h, string t, int d)
: width(w), height(h), depth(d), title(t)
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_WM_SetCaption(title.c_str(), NULL);
refresh();
}
void
SDLScreen::refresh()
{
screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE);
}
The selection rectangle for the active menu item should be blue, but it shows up in black. The file selection.bmp is also all black.
Edit 2: I found out what created the problem. The selectionRect was set relative to the screen, while the selectionCanvas had the width and height of a particular menu item. So, the filling was done out of bounds of the selectionCanvas. Adding separate SDL_Rect for filling solved the problem.
SDL_Rect fillRect;
fillRect.x = 0;
fillRect.y = 0;
fillRect.w = selectionRect->w;
fillRect.h = selectionRect->h;
SDL_FillRect(selectionCanvas, &fillRect, selectionColor);
// and later...
SDL_BlitSurface(selectionCanvas, NULL, canvas, selectionRect);
You inverted source and destination. To blit on screen, it should be
SDL_BlitSurface(layer, NULL, screen, NULL);
doc for SDL_BlitSurface