Jump to content
  • Advertisement

Search the Community

Showing results for tags 'SDL'.

The search index is currently processing. Current results may not be complete.


More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Categories

  • Audio
    • Music and Sound FX
  • Business
    • Business and Law
    • Career Development
    • Production and Management
  • Game Design
    • Game Design and Theory
    • Writing for Games
    • UX for Games
  • Industry
    • Interviews
    • Event Coverage
  • Programming
    • Artificial Intelligence
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Engines and Middleware
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
  • Archive

Categories

  • Audio
  • Visual Arts
  • Programming
  • Writing

Categories

  • Game Developers Conference
    • GDC 2017
    • GDC 2018
  • Power-Up Digital Games Conference
    • PDGC I: Words of Wisdom
    • PDGC II: The Devs Strike Back
    • PDGC III: Syntax Error

Forums

  • Audio
    • Music and Sound FX
  • Business
    • Games Career Development
    • Production and Management
    • Games Business and Law
  • Game Design
    • Game Design and Theory
    • Writing for Games
  • Programming
    • Artificial Intelligence
    • Engines and Middleware
    • General and Gameplay Programming
    • Graphics and GPU Programming
    • Math and Physics
    • Networking and Multiplayer
  • Visual Arts
    • 2D and 3D Art
    • Critique and Feedback
  • Community
    • GameDev Challenges
    • GDNet+ Member Forum
    • GDNet Lounge
    • GDNet Comments, Suggestions, and Ideas
    • Coding Horrors
    • Your Announcements
    • Hobby Project Classifieds
    • Indie Showcase
    • Article Writing
  • Affiliates
    • NeHe Productions
    • AngelCode
  • Topical
    • Virtual and Augmented Reality
    • News
  • Workshops
    • C# Workshop
    • CPP Workshop
    • Freehand Drawing Workshop
    • Hands-On Interactive Game Development
    • SICP Workshop
    • XNA 4.0 Workshop
  • Archive
    • Topical
    • Affiliates
    • Contests
    • Technical
  • GameDev Challenges's Topics
  • For Beginners's Forum

Calendars

  • Community Calendar
  • Games Industry Events
  • Game Jams
  • GameDev Challenges's Schedule

Blogs

There are no results to display.

There are no results to display.

Product Groups

  • GDNet+
  • Advertisements
  • GameDev Gear

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


About Me


Website


Industry Role


Twitter


Github


Twitch


Steam

Found 37 results

  1. I am somewhat new to game development and trying to create a basic 3d engine. I have managed to set up a first person camera and it seems to be working fine for the most part. While I am able to look up, down, left and right just fine the camera is constrained to the mouse movement in the window (i.e when the mouse reaches edges of the window it discontinues camera rotation and mouse is out of window bounds. I tried to use SDL_WarpMouseInWindow(window, center.x,center.y) but when I do this then it messes up the camera and the camera is stuck, even though there is some slight movement of the camera, it keeps going back to the center. void Camera::UpdateViewByMouse(SDL_Window &window, glm::vec2 mousePosition) { float xDistanceFromWindowCenter = mousePosition.x - ((float)1024 / 2) ; float yDistanceFromWindowCenter = ((float)720 / 2) - mousePosition.y; yaw = xDistanceFromWindowCenter * cameraRotationSpeed; pitch = yDistanceFromWindowCenter * cameraRotationSpeed; SDL_WarpMouseInWindow(&window, 1024 / 2, 768 / 2); } i’ve been stuck on this for far too long. any help would be much appreciated i have also tried relative mouse movement, and .xrel and .yrel to avail. polling mouse state with sdl_event. I do also know that SDL_WarpMouseInWindow makes change to event and have tried also ignore and reenabling to no avail
  2. I am at the first year of diploma and I am planing to make a nice small 2D or 3D First Person Shooter game . As I mentioned I am just at first year in IT ,I Dont know much about game developing but I do know lots of more things that normal 1st and even 3rd year students . I Know Java,C,C++ and little bit of python and GTK+ framework . I am currently trying to learn SDL and Qt with C++. I will also happily learn new technology if required to make games. Now my main Question's are:- How much time will it take to make SMALL 2D game as a single person in SDL while LEARNING SDL ? How much time will it take to make SMALL 3D game as a single person in SDL while LEARNING SDL ? Will learning Qt help me make games faster or with High performance ? My main platform is Linux and Android.I don't care if It runs on windows or Mac but it should run fine on Linux . Thanks in advance
  3. Hello, I'm programming a simple rougelike video game for fun. I'm running into a very difficult problem with my room generation code, specifically the part that deals with the maze-like hallway to connect the randomly placed rooms inside a dungeon, using the depth-first search method. The code I've written is kinda long and probably hard to read, but I seriously cannot figure out what is causing the issue so try to bear with me please. Below is the header file for the Floor class, which generates the floor of the dungeon. #ifndef FLOOR_H_ #define FLOOR_H_ #include <iostream> #include <vector> #include <algorithm> #include "Cell.h" class Floor { private: int attempts; //Amount of attempts it tries to place a room before giving up. More attempts = more cramped. int maxdoor; //Maximum amount of doors on each room int maxroom; //Maximum number of rooms. 0 for 999. int maxheight, minheight; int maxwidth, minwidth; int maxbigroom; std::vector<std::vector<Cell> > region; //A collection of regions. A region is a collection of cells (rooms & hallway) std::vector<Cell> temp_region; //Used to fill the region. std::vector<Cell> temp_maze; std::vector<Cell> maze; public: Floor(); void init(int attempts, int maxdoor, int maxroom, int maxwidth, int minwidth, int maxheight, int minheight, int maxbigroom); void gen(Cell cell[120][60], SDL_Texture* tex); bool check_walls(Cell cell[120][60], int* x, int* y); }; #endif The main thing that is important in this header is the temp_maze vector, which is used to keep track of the current section of the maze that has been carved out, so that when the maze hits a dead end it can back track. is the Cell is a class that represents a cell in the 2D grid that the player can move on. For the issue of this post, just think of each Cell as having an X integer, a Y integer, and a Bool to keep track of whether or not the cell is opened up. Below is the part of the gen function that deals with the hallway generation. //Hallway Generation int cur_x, cur_y; //Current cell being tested bool time_to_break; for (int i = 1; i < 119; i++) { for (int j = 1; j < 59; j++) { if (cell[i][j].return_blockade() == true && cell[i + 1][j].return_blockade() == true && cell[i][j + 1].return_blockade() == true && cell[i - 1][j].return_blockade() == true && cell[i][j - 1].return_blockade() == true) { //Start of a path cur_x = i; cur_y = j; while (true) { cell[cur_x][cur_y].set_bloc(false); //Opens up cell cell[cur_x][cur_y].set_tex(tex); cell[cur_x][cur_y].set_default_tex(tex); temp_maze.push_back(cell[cur_x][cur_y]); if (check_walls(cell, &cur_x, &cur_y) == false) { std::cout << "Entering nospace" << std::endl; std::cout << "Size of k: " << temp_maze.size() << std::endl; for (int k = temp_maze.size() - 1; k > -1; k--) { int xte = temp_maze[k].return_rect().x / 15; int yte = temp_maze[k].return_rect().y / 15; std::cout << "k: " << k << std::endl; std::cout << "rect_x: "<< temp_maze[k].return_rect().x<< " rect_y : "<< temp_maze[k].return_rect().y<< std::endl; std::cout << "x_te: " << xte << " y_te: " << yte << std::endl; if (check_walls(cell, &xte, &yte) == true) { cur_x = xte; cur_y = yte; std::cout << "Exiting nospace via newblock" << std::endl; break; } if (k == 0) { time_to_break = true; std::cout << "Exiting nospace via noviableblock" << std::endl; break; } } } if (time_to_break == true) { time_to_break = false; temp_maze.clear(); break; } } } } } The broad idea is that, starting from the top-left cell, we scroll through them until we find a cell that is not blocked, nor has any neighbors that are blocked. Than we open that cell up, add it to the temp_maze vector, and check whether it has any viable neighbors. If it does, it moves cur_y and cur_x to that new cell and repeats. If it doesn't have any viable neighbors, than it goes through the temp_maze vector until either it finds a cell that has viable neighbors, or it reaches the end of the vector. This is accomplished with the check_walls function. bool Floor::check_walls(Cell cell[120][60], int* x, int* y) { int ori_x = *x; int ori_y = *y; std::cout << "Entering checkwalls with x: " << ori_x << " y: " << ori_y << std::endl; if (cell[ori_x][ori_y].return_blockade() == true) { std::cout << "Checkwalls returns false due to being blocked" << std::endl; return false; } while (true) { *x = ori_x; *y = ori_y; bool upblock, rightblock, downblock, leftblock; int sidecount = 0; int dir = rand() % 4; if (dir == 0) { *y = (*y) - 1; } else if (dir == 1) { *x = (*x) - 1; } else if (dir == 2) { *y = (*y) + 1; } else if (dir == 3) { *x = (*x) + 1; } if (*x <= 0 || *y <= 0) { sidecount = 8; dir = 5; *x = ori_x; *y = ori_y; } if (cell[*x + 1][*y].return_blockade() == false) { sidecount++; } if (cell[*x - 1][*y].return_blockade() == false) { sidecount++; } if (cell[*x][*y + 1].return_blockade() == false) { sidecount++; } if (cell[*x][*y - 1].return_blockade() == false) { sidecount++; } if (sidecount <= 1) { std::cout << "Checkwalls returns true" << std::endl; return true; } else { if (dir == 0) { upblock = true; } else if (dir == 1) { leftblock = true; } else if (dir == 2) { downblock = true; } else if (dir == 3) { rightblock = true; } } if (upblock == true && leftblock == true && downblock == true && rightblock == true) { *x = ori_x; *y = ori_y; std::cout << "Checkwalls returns false" << std::endl; return false; } } } The basic idea here is that if one of the neighbors are available, than it moves x & y to that cell and return true, and if there are none, than return false. The problem is that when I run this the temp_maze function seems to get filled with the same cell, and time_to_break never gets set to true, as the vector seems to never end. Once again I understand this is kind of a lot but I have looked at this for a couple days now and have no idea what i am doing wrong, so any help would be very much appreciated.
  4. For those that don't know me. I am the individual who's two videos are listed here under setup for https://wiki.libsdl.org/Tutorials I also run grhmedia.com where I host the projects and code for the tutorials I have online. Recently, I received a notice from youtube they will be implementing their new policy in protecting video content as of which I won't be monetized till I meat there required number of viewers and views each month. Frankly, I'm pretty sick of youtube. I put up a video and someone else learns from it and puts up another video and because of the way youtube does their placement they end up with more views. Even guys that clearly post false information such as one individual who said GLEW 2.0 was broken because he didn't know how to compile it. He in short didn't know how to modify the script he used because he didn't understand make files and how the requirements of the compiler and library changes needed some different flags. At the end of the month when they implement this I will take down the content and host on my own server purely and it will be a paid system and or patreon. I get my videos may be a bit dry, I generally figure people are there to learn how to do something and I rather not waste their time. I used to also help people for free even those coming from the other videos. That won't be the case any more. I used to just take anyone emails and work with them my email is posted on the site. I don't expect to get the required number of subscribers in that time or increased views. Even if I did well it wouldn't take care of each reoccurring month. I figure this is simpler and I don't plan on putting some sort of exorbitant fee for a monthly subscription or the like. I was thinking on the lines of a few dollars 1,2, and 3 and the larger subscription gets you assistance with the content in the tutorials if needed that month. Maybe another fee if it is related but not directly in the content. The fees would serve to cut down on the number of people who ask for help and maybe encourage some of the people to actually pay attention to what is said rather than do their own thing. That actually turns out to be 90% of the issues. I spent 6 hours helping one individual last week I must have asked him 20 times did you do exactly like I said in the video even pointed directly to the section. When he finally sent me a copy of the what he entered I knew then and there he had not. I circled it and I pointed out that wasn't what I said to do in the video. I didn't tell him what was wrong and how I knew that way he would go back and actually follow what it said to do. He then reported it worked. Yea, no kidding following directions works. But hey isn't alone and well its part of the learning process. So the point of this isn't to be a gripe session. I'm just looking for a bit of feed back. Do you think the fees are unreasonable? Should I keep the youtube channel and do just the fees with patreon or do you think locking the content to my site and require a subscription is an idea. I'm just looking at the fact it is unrealistic to think youtube/google will actually get stuff right or that youtube viewers will actually bother to start looking for more accurate videos.
  5. Jeff de Anda

    C++ SDL_Rect Scope

    Question about SDL_Rect scope. Say I have a member function like so. void drawRect(int x, int y, int w, int y) { SDL_Rect r = {x, y, w, h}; SDL_RenderDrawRect(m_renderer, &r); } Will it cause problems if SDL_Rect goes out of scope before calling SDL_RenderPresent? I cannot tell if the values are copied from SDL_Rect when calling SDL_RenderDrawRect or if internally SDL is storing the pointer until SDL_RenderPresent is called. Thanks!
  6. Hey, I've a minor problem that prevents me from moving forward with development and looking to find a way that could solve it. Overall, I'm having a sf::VertexArray object and looking to reander a shader inside its area. The problem is that the shader takes the window as canvas and only becomes visible in the object range which is not what I'm looking for.. Here's a stackoverflow links that shows the expected behaviour image. Any tips or help is really appreciated. I would have accepted that answer, but currently it does not work with #version 330 ...
  7. I can't get SDL to make any rectangles on my Mac. The program I wrote worked completely fine on a Windows computer, but whenever I call the SDL_FillRect function on my Mac, nothing appears on the screen. I suspect this may be caused by a compilation issue. I'm using SDL through Frameworks. Inserted below is my terminal command and my code: g++ example.cpp -I/Library/Frameworks/SDL2.framework/Headers -F/Library/Frameworks -framework SDL2 #include <SDL2/SDL.h> #include <iostream> #include <stdio.h> const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; const int PLAYER_WIDTH = 20; const int PLAYER_HEIGHT = 20; SDL_Window* w = NULL; SDL_Surface* s = NULL; SDL_Renderer* r = NULL; SDL_Rect BG = {0,0,SCREEN_WIDTH,SCREEN_HEIGHT}; bool init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Couldn't initialize. error: %s\n", SDL_GetError() ); return false; } else { w = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if(w == NULL) { printf("Couldn't make window. error:%s\n", SDL_GetError() ); return false; } else { s = SDL_GetWindowSurface(w); r = SDL_CreateRenderer(w,-1,SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); SDL_SetRenderDrawColor(r,0,0,0,0); return true; } } } void close() { SDL_FreeSurface(s); SDL_DestroyWindow(w); SDL_DestroyRenderer(r); SDL_Quit(); } class Player { private: int x; int y; int xvel; int yvel; int acceleration; SDL_Rect collider; public: bool landed; Player() { x = 0; y = SCREEN_HEIGHT - PLAYER_HEIGHT; xvel = 0; yvel = 0; acceleration = -1; collider.x = x; collider.y = y; collider.w = PLAYER_WIDTH; collider.h = PLAYER_HEIGHT; landed = true; } int getx() { return x; } int gety() { return y; } void setx(int num) { x = num; } void sety(int num) { y = num; } void setyvel(int num) { yvel += num; } void setxvel(int num) { xvel += num; } void move() { x += xvel; if( (y + PLAYER_HEIGHT) > SCREEN_HEIGHT) { y = SCREEN_HEIGHT - PLAYER_HEIGHT; yvel = 0; landed = true; } else { if(landed != true) { //so sorry for the bad code, this was the only idea i had to debug "bouncing" of the player y += yvel; yvel = yvel - acceleration; } } collider.x = x; collider.y = y; } void render() { SDL_SetRenderDrawColor(r,255,255,255,255); SDL_RenderFillRect(r,&collider); SDL_SetRenderDrawColor(r,0,0,0,255); } }; int main(int argc, char *argv[]) { bool quit = false; SDL_Event e; //event for event polling Player p; int count = 0; if(init() == false) { printf("Init failed: %s\n", SDL_GetError()); } else { while(quit == false ) { while( SDL_PollEvent(&e) != 0) { if(e.type == SDL_QUIT) { quit = true; } if(e.type == SDL_KEYDOWN) { switch(e.key.keysym.sym) { case SDLK_LEFT: if(e.key.repeat == 0) { p.setxvel(-10); } break; case SDLK_RIGHT: if(e.key.repeat == 0) { p.setxvel(10); } break; case SDLK_UP: if(count < 5) { p.setyvel(-3); ++count; } p.landed = false; break; } } if(e.type == SDL_KEYUP && e.key.repeat == 0) { switch(e.key.keysym.sym) { case SDLK_LEFT: p.setxvel(10); break; case SDLK_RIGHT: p.setxvel(-10); break; case SDLK_UP: count = 0; break; } } } SDL_RenderClear(r); SDL_RenderFillRect(r,&BG); p.move(); p.render(); SDL_RenderPresent(r); } } close(); Please help me to get it working, I have no idea what's going on. I have SDL 2.0.7 and my Mac is OS X 10.10.3.
  8. SDL isn't drawing any rectangles to the window in a Mac OS X environment, and I have no idea why. I've tried in both a Windows and an Ubuntu environment, and the rectangles are being drawn in those environments. I'm using SDL by using frameworks. This is what I write into the terminal: g++ example.cpp -I/Library/Frameworks/SDL2.framework/Headers -F/Library/Frameworks -framework SDL2 This is the actual code of the program: #include <SDL2/SDL.h> #include <iostream> #include <stdio.h> const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; const int PLAYER_WIDTH = 20; const int PLAYER_HEIGHT = 20; SDL_Window* w = NULL; SDL_Surface* s = NULL; SDL_Renderer* r = NULL; SDL_Rect BG = {0,0,SCREEN_WIDTH,SCREEN_HEIGHT}; bool init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Couldn't initialize. error: %s\n", SDL_GetError() ); return false; } else { w = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if(w == NULL) { printf("Couldn't make window. error:%s\n", SDL_GetError() ); return false; } else { s = SDL_GetWindowSurface(w); r = SDL_CreateRenderer(w,-1,SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); SDL_SetRenderDrawColor(r,0,0,0,0); return true; } } } void close() { SDL_FreeSurface(s); SDL_DestroyWindow(w); SDL_DestroyRenderer(r); SDL_Quit(); } class Player { private: int x; int y; int xvel; int yvel; int acceleration; SDL_Rect collider; public: bool landed; Player() { x = 0; y = SCREEN_HEIGHT - PLAYER_HEIGHT; xvel = 0; yvel = 0; acceleration = -1; collider.x = x; collider.y = y; collider.w = PLAYER_WIDTH; collider.h = PLAYER_HEIGHT; landed = true; } int getx() { return x; } int gety() { return y; } void setx(int num) { x = num; } void sety(int num) { y = num; } void setyvel(int num) { yvel += num; } void setxvel(int num) { xvel += num; } void move() { x += xvel; if( (y + PLAYER_HEIGHT) > SCREEN_HEIGHT) { y = SCREEN_HEIGHT - PLAYER_HEIGHT; yvel = 0; landed = true; } else { if(landed != true) { //so sorry for the bad code, this was the only idea i had to debug "bouncing" of the player y += yvel; yvel = yvel - acceleration; } } collider.x = x; collider.y = y; } void render() { SDL_SetRenderDrawColor(r,255,255,255,255); SDL_RenderFillRect(r,&collider); SDL_SetRenderDrawColor(r,0,0,0,255); } }; int main(int argc, char *argv[]) { bool quit = false; SDL_Event e; //event for event polling Player p; int count = 0; if(init() == false) { printf("Init failed: %s\n", SDL_GetError()); } else { while(quit == false ) { while( SDL_PollEvent(&e) != 0) { if(e.type == SDL_QUIT) { quit = true; } if(e.type == SDL_KEYDOWN) { switch(e.key.keysym.sym) { case SDLK_LEFT: if(e.key.repeat == 0) { p.setxvel(-10); } break; case SDLK_RIGHT: if(e.key.repeat == 0) { p.setxvel(10); } break; case SDLK_UP: if(count < 5) { p.setyvel(-3); ++count; } p.landed = false; break; } } if(e.type == SDL_KEYUP && e.key.repeat == 0) { switch(e.key.keysym.sym) { case SDLK_LEFT: p.setxvel(10); break; case SDLK_RIGHT: p.setxvel(-10); break; case SDLK_UP: count = 0; break; } } } SDL_RenderClear(r); SDL_RenderFillRect(r,&BG); p.move(); p.render(); SDL_RenderPresent(r); } } close(); Please help me to get it working, I have no idea what's going on. I have SDL 2.0.7 and my Mac is OS X 10.10.3.
  9. I have a simple openGL engine using SDL working. I'm not using any SDL_Image stuff, its all just openGL. I've made 2d tilemap levels with a .txt file before by reading in the characters and using a switch statement to assign them to various textures and using their position in the file to render them. This method works fine and produces no graphical glitches. Then I made a .tmx map in Tiled and used TmxParser to read the file into my program, and I'm able to render the map properly to the screen, but when I move up and down these black lines start to appear between the tiles. The map loads in fine at first, its only once I start moving the camera around that it happens, and its only when the camera moves up or down. I made a video to show exactly what I'm seeing, I see a lot of these type of issues when searching google but nothing that matches whats happening to me. I'm not even sure if this is a problem with the code or what it could be so I don't know of any code to include. This problem also happened to me when I was using Unity and importing a Tiled map with Tiled2Unity. In unity there were long horizontal line glitches on the tilemap, and now its happening to me again in c++, is this something to do with Tiled? Has anyone encountered this before or know a solution? Any help would be greatly appreciated, I feel stuck on this issue.
  10. ¡ Aloha ! Summary A project ? 2 actually ! The main one is a real time simulation/strategy 2D game coded in C/C++/SDL where for the moment you control settlers on an island. The other project is a text based browser game and its features will be ported. Goals Have fun : Experiment, wild my creativity… Rapid prototyping : Gameplay first (Graphics credit : openclipart) Satisfy my needs as a player and make others happy Contribute to an open source game like Unknown Horizons or launch my own Features Hybrid gameplay : Automatic (God game) or manual (RTS) actions RPG-like attributes : HP, sex… Survival elements : Gather or fish renewable resources to eat and drink or… die !! Basic interaction : Minimal interface and keyboard shortcuts Rudimentary engine : Tile-based, path finding and super ultra turbo procedural generation Multilingual : English and French Screenshots In the first one, on Day 3, the camp has some water but no food yet. There's an explorer, 2 gatherers and one fishman. On Day 1314 the remaining settlers are fishing and gathering from spots that aren't depleted. Todo Gameplay, gameplay, gameplay GUI improvements Bigger maps Scrolling and zooming … Plenty of cool and interesting stuff !! References Series : Anno, The Settlers, City Building (Caesar, Pharaoh & Zeus) and Age of Empires Classics : SimCity, Civilization… and Populous of course !! Robinsonades
  11. GlPortal is a free and open source first person 3D teleportation based puzzle game and platformer. But we have already integrated a physics engine and are planning for some physics based puzzles. We want to improve our Visual Studio support. Check out this project: https://github.com/kungfooman/glportal-vs You can chat with us on gitter https://gitter.im/GlPortal/glPortal
  12. Hi everyone, I'm Michele (not Michelle, I'm a guy ok? Just call me Mike), italian computer engineer with a strong passion about video game development. I decided to start a blog about making games from scratch using SDL and C. Why am I doing this? First of all, because I strongly believe that you don't need an engine to realize a MVP of your game. I will make games starting from a very basic idea to the first release, discussing the code and the choices. Name of the blog is "Making Games The Wrong Way", which provocatively means that we don't want to over-think the code structure and, above all, we don't want to do premature optimizations. Code will be plain, not beautiful for sure, but it will get our job done. I hope to see many followers from here. It is going to be a nice learning experience both for me and for you Here's the link: https://michelerullo.wordpress.com/ See you there!
  13. lilington

    Soul of Mask close to release

    Hey, Me again, I got some problem with SDL2_mixer on macOs, actually I am thinking about cancelling MacOs version as I found no solution to play sounds in this platform. Looks like we will stick with Windows and Linux. Good news, the development is about to be close now. and i provide 3 videos for Tutorial, Mask power presentation, and an easy level to show the gameplay. Tutorial : Mask Presentation: Gameplay. Before each level, the level takes something like 1 to 5 seconds to load depending on the computer, so I added loading screen that presents all the different characters in the game. here you have one. hope you will like it.
  14. lilington

    Soul of Mask

    Hi, My name is Alain Perrin,I come here to present my project (actually almost finished) of game. Soul Of Mask already announced on steam. It is, unfortunately, a one-man job. 3 years of pleasure and nightmares. But it is still a joy to work on it. I was supposed to start talking about this game at least one year ago it is probably a big mistake a made. Anyways better late than never. It is a game about a mask supposed to collect one object and avoid enemies on the map with Pacman view. The main character has to take a mask to be able to collect those object. Those masks have some powers like burning enemies, feezing... by using a power of a mask it is lost. The game is supposed to be released on steam at the end of this month (nov 25th 2017). The game is writen C/SDL, graphics assets are made with gimp and audio lmms/audacity. current status of a game is debug/testing. More info are coming soon. for the moment you can have a look at indiedb and steam Video of the game gameplay:
  15. Does anyone have any experience (good or bad) using Docker for developing a game with SDL and/or C++? I can see it being useful for sharing the build environment, though games typically being compiled, GUI applications makes Docker seem like a bit more of a foreign concept.
  16. I can't get SDL to make any rectangles on my Mac. The program I wrote worked completely fine on a Windows computer, but whenever I call the SDL_FillRect function on my Mac, nothing appears on the screen. I suspect this may be caused by a compilation issue. I tried to install SDL Unix-style using Homebrew. Inserted below is what I write into the terminal and my code. g++ -o main test.cpp -L/usr/local/Cellar/sdl2/2.0.6/lib -lSDL2 -lSDL2main -I/usr/local/Cellar/sdl2/2.0.6/include/SDL2 #include <SDL.h> #include <iostream> #include <stdio.h> const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; const int PLAYER_WIDTH = 20; const int PLAYER_HEIGHT = 20; SDL_Window* w = NULL; SDL_Surface* s = NULL; SDL_Renderer* r = NULL; SDL_Rect BG = {0,0,SCREEN_WIDTH,SCREEN_HEIGHT}; bool init() { if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Couldn't initialize. error: %s\n", SDL_GetError() ); return false; } else { w = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if(w == NULL) { printf("Couldn't make window. error:%s\n", SDL_GetError() ); return false; } else { s = SDL_GetWindowSurface(w); r = SDL_CreateRenderer(w,-1,SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); SDL_SetRenderDrawColor(r,0,0,0,0); return true; } } } void close() { SDL_FreeSurface(s); SDL_DestroyWindow(w); SDL_DestroyRenderer(r); SDL_Quit(); } class Player { private: int x; int y; int xvel; int yvel; int acceleration; SDL_Rect collider; public: bool landed; Player() { x = 0; y = SCREEN_HEIGHT - PLAYER_HEIGHT; xvel = 0; yvel = 0; acceleration = -1; collider.x = x; collider.y = y; collider.w = PLAYER_WIDTH; collider.h = PLAYER_HEIGHT; landed = true; } int getx() { return x; } int gety() { return y; } void setx(int num) { x = num; } void sety(int num) { y = num; } void setyvel(int num) { yvel += num; } void setxvel(int num) { xvel += num; } void move() { x += xvel; if( (y + PLAYER_HEIGHT) > SCREEN_HEIGHT) { y = SCREEN_HEIGHT - PLAYER_HEIGHT; yvel = 0; landed = true; } else { if(landed != true) { y += yvel; yvel = yvel - acceleration; } } collider.x = x; collider.y = y; } void render() { SDL_SetRenderDrawColor(r,255,255,255,255); SDL_RenderFillRect(r,&collider); SDL_SetRenderDrawColor(r,0,0,0,255); } }; int main(int argc, char *argv[]) { bool quit = false; SDL_Event e; //event for event polling Player p; int count = 0; if(init() == false) { printf("Init failed: %s\n", SDL_GetError()); } else { while(quit == false ) { while( SDL_PollEvent(&e) != 0) { if(e.type == SDL_QUIT) { quit = true; } if(e.type == SDL_KEYDOWN) { switch(e.key.keysym.sym) { case SDLK_LEFT: if(e.key.repeat == 0) { p.setxvel(-10); } break; case SDLK_RIGHT: if(e.key.repeat == 0) { p.setxvel(10); } break; case SDLK_UP: if(count < 5) { p.setyvel(-3); ++count; } p.landed = false; break; } } if(e.type == SDL_KEYUP && e.key.repeat == 0) { switch(e.key.keysym.sym) { case SDLK_LEFT: p.setxvel(10); break; case SDLK_RIGHT: p.setxvel(-10); break; case SDLK_UP: count = 0; break; } } } SDL_RenderClear(r); SDL_RenderFillRect(r,&BG); p.move(); p.render(); SDL_RenderPresent(r); } } close(); }
  17. https://github.com/ingframin/CPongC/tree/master I have a bug that make my game crash outside of code::blcoks but run just fine in it. My guess is that I have an uninitialized pointer somewhere that is initialized by codeblocks when I run the code inside it. Can someone please try and let me know? I use codeblocks + GCC under Windows.
  18. Hello everyone, For learning purposes, I want to try to make a small graphical snake game in assembly. I've thought about where to start and which tools to use and personally I thought about using SDL and C to handle the keyboard input and the graphical output, but I would really like to know from other if there are better/easier ways to do this. Thanks
  19. Hi there fellas, I'm the new guy in need of help. I'm writing a simple tangram puzzle using c++ and sdl2. Goal of the game is to fit pieces on the grid. Piece movement is done via mouse drag and drop. The problem I'm having is when the cursor is over overlapping objects and I click and drag every shape under it gets dragged. I need some kind of check for object on top or something like that (I'm thinking it has to do something with height). Any help would be greatly appreciated. I've made Vec2 class that holds two int values for anything that has x and y values. Here is GameObject code that I use for puzzle pieces : void GameObject::render() { SDL_SetRenderDrawColor(Game::Instance()->getRenderer(), m_color.r, m_color.g, m_color.b, m_color.a); SDL_Rect rects[] = { m_position.getX(), m_position.getY(), m_dimension.getX(), m_dimension.getY(), m_position2.getX(), m_position2.getY(), m_dimension2.getX(), m_dimension2.getY() }; SDL_RenderFillRects(Game::Instance()->getRenderer(), rects, 2); SDL_RenderDrawRects(Game::Instance()->getRenderer(),rects, 2); } void GameObject::update() { if (InputHandler::Instance()->getMouseButtonState(0) && intersects(m_position, m_dimension, *InputHandler::Instance()->getMouseButtonPosition()) || intersects(m_position2, m_dimension2, *InputHandler::Instance()->getMouseButtonPosition())) { offset = (*InputHandler::Instance()->getMouseButtonPosition() - m_position); offset2 = (*InputHandler::Instance()->getMouseButtonPosition() - m_position2); dragging = true; } else if (!InputHandler::Instance()->getMouseButtonState(0) && dragging) { offset = Vec2(0,0); offset2 = Vec2(0,0); dragging = false; } if(dragging){ m_position = *InputHandler::Instance()->getMousePosition() - offset; m_position2 = *InputHandler::Instance()->getMousePosition() - offset2; } } bool GameObject::intersects(Vec2 object, Vec2 dimensions, Vec2 mouse) { if(mouse.getX() < object.getX() || mouse.getY() < object.getY()) { return false; } if(mouse.getX() > object.getX() + dimensions.getX() || mouse.getY() > object.getY() + dimensions.getY()) { return false; } return true; } And here is it being called in the game singleton. void Game::render() { SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 0); SDL_RenderClear(m_pRenderer); for (int i = 0; i < m_gameObjects.size(); i++) { m_gameObjects[i]->render(); } SDL_RenderPresent(m_pRenderer); } void Game::update() { for (int i = m_gameObjects.size()-1; i >= 0; i--) { m_gameObjects[i]->update(); } } And here is input handler, also a singleton: void InputHandler::update() { SDL_Event event; while (SDL_PollEvent(&event)) { m_keystates = SDL_GetKeyboardState(0); if (event.type == SDL_QUIT) { Game::Instance()->quit(); } if (event.type == SDL_MOUSEBUTTONDOWN) { m_mouseButtonPosition->setX(event.button.x); m_mouseButtonPosition->setY(event.button.y); if (event.button.button == SDL_BUTTON_LEFT) { m_mouseButtonStates[LEFT] = true; } if (event.button.button == SDL_BUTTON_MIDDLE) { m_mouseButtonStates[MIDDLE] = true; } if (event.button.button == SDL_BUTTON_RIGHT) { m_mouseButtonStates[RIGHT] = true; } } if (event.type == SDL_MOUSEBUTTONUP) { if (event.button.button == SDL_BUTTON_LEFT) { m_mouseButtonStates[LEFT] = false; } if (event.button.button == SDL_BUTTON_MIDDLE) { m_mouseButtonStates[MIDDLE] = false; } if (event.button.button == SDL_BUTTON_RIGHT) { m_mouseButtonStates[RIGHT] = false; } } if (event.type == SDL_MOUSEMOTION) { m_mousePosition->setX(event.motion.x); m_mousePosition->setY(event.motion.y); } } }
  20. Dzuvan

    Wierd bug

    Hello, I'm having a rather strange bug. I'm making puzzle game. When the game starts(PlayState) for the first time pieces are indeed correctly placed, but after that sometimes they appear fine and most of the time only half of each piece is present ( I'm composing them out of 2 rectangles). The other parts appear at coordinates like this : Part2: X[1] : 842150923, Y[1]: 842150691. It happens even if I don' t use rand(). I'm using a state machine: PlayState can go to: - pause state PauseState can go to: - Resume - Main Menu stateMain MenuState can go to: - PlayState - Exit I'm following a book "SDL Game Development" by Shaun Mitchell (btw It's full of bugs). bool PlayState::onEnter() { int left_x = 600 + (rand() % static_cast<int>(750 - 600 + 1)); int left_y = 500 + (rand() % static_cast<int>(500 - 100 + 1)); Vec2 dimension = Vec2(100, 200); int right_x = left_x + 100; int right_y = left_y; Vec2 dimension_2 = Vec2(100, 200); SDL_Color color1 = { 255, 0, 0, 0 }; Piece* piece = new Piece(Vec2(left_x, left_y), Vec2(right_x, right_y), dimension, dimension_2, color1); // Piece 2 int i_left_x = 600 + (rand() % static_cast<int>(750 - 600 + 1)); int i_left_y = 500 + (rand() % static_cast<int>(500 - 100 + 1)); Vec2 dimension_i1 = Vec2(100, 100); int i_right_x = i_left_x; int i_right_y = i_left_y + 100; Vec2 dimension_i2 = Vec2(100, 100); SDL_Color color3 = { 0, 0, 255, 0 }; Piece* piece3 = new Piece(Vec2(i_left_x, i_left_y), Vec2(i_right_x, i_right_y), dimension_i1, dimension_i2, color3); // and so on until I have 7 pieces. } // ... void PlayState::update() { if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE)) { Game::Instance()->getStateMachine()->pushState(new PauseState()); } for (unsigned int i = 0; i < m_pieces.size(); i++){ m_pieces[i]->update(); } The issue occurs when I go from MainMenuState to PlayState after PauseState. I'll provide additional info if needed. Thanks in advance.
  21. I created a small test application where I handle the SDL_CONTROLLERDEVICEADDED and SDL_CONTROLLERDEVICEREMOVED events, and output information about the controller being added/removed, based on the information in this blog. I have two controllers connected to my PC, an Xbox 360 controller and a Logitech controller. What I found is that if they are both active and awake it produces the expected output, but if either one or both of them are asleep, it outputs the wrong name under certain conditions. I don't want to be overly verbose and go over every configuration I tested, but one example is if I start the application with both controllers in sleep mode, it fires the SDL_CONTROLLERDEVICEADDED for the Logitech controller but not the Xbox controller at application startup (The event for the Xbox control only happens when it is awakened), and then when I unplug/plug in the Logitech controller's USB receiver, it shows the device name as "X360" every time, until I wake them both up, at which point it outputs the correct name again. Perhaps I'm worrying too much about this, as most people probably don't mix and match controllers and likely only use one, but I just found it curious. I'm wondering if it might be a bug in SDL2, or if maybe there is some insight someone might have related to xbox controllers and how they behave in sleep mode. Here is the relevant code if anyone's interested: struct SdlGamepad { SDL_GameController* controller; SDL_Joystick* joystick; SDL_JoystickID joystickId; std::string deviceName; int deviceId; }; std::map<SDL_JoystickID, SdlGamepad> joystickIdToGamepadMap; SDL_Event event; bool hasQuit = false; while (hasQuit == false) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_CONTROLLERDEVICEADDED: { std::cout << "Controller device added." << std::endl; if (SDL_IsGameController(event.cdevice.which)) { SdlGamepad gamepad; gamepad.controller = SDL_GameControllerOpen(event.cdevice.which); gamepad.joystick = SDL_GameControllerGetJoystick(gamepad.controller); gamepad.joystickId = SDL_JoystickInstanceID(gamepad.joystick); std::string deviceName = SDL_GameControllerName(gamepad.controller); gamepad.deviceName = deviceName; gamepad.deviceId = event.cdevice.which; joystickIdToGamepadMap[gamepad.joystickId] = gamepad; std::cout << "Controller device name = " << gamepad.deviceName << std::endl << "Controller device ID = " << gamepad.deviceId << std::endl << "Joystick device ID = " << gamepad.joystickId << std::endl << std::endl; } break; } case SDL_CONTROLLERDEVICEREMOVED: { std::cout << "Controller device removed." << std::endl; SdlGamepad gamepad = joystickIdToGamepadMap[event.cdevice.which]; std::cout << "Controller device name = " << gamepad.deviceName << std::endl << "Controller device ID = " << gamepad.deviceId << std::endl << "Joystick device ID = " << gamepad.joystickId << std::endl << std::endl; SDL_GameControllerClose(gamepad.controller); joystickIdToGamepadMap.erase(event.cdevice.which); break; } case SDL_QUIT: { hasQuit = true; break; } } } }
  22. Hey everybody, A little over a month ago, I made a post asking for help with my Missile Command game that I was making with regards to getting the Cannon to angle properly, and I was very pleased with all of the support. It really lit a fire under me (even moreso before I worked up the courage to ask the first time). Well, the game is not finished yet, but I have made a lot of progress since then ( it's very motivating ) and I've been able to work through the code and logic for shooting missiles from the cannon. The missile logic is almost ready, but there is one small bug that I discovered last week that has been wracking my brain non-stop, so I'm posting a new topic here. Here is an animated GIF of the missile behavior so far, in this shot, it's working as expected when you click the Left mouse button to fire one missile at a time: https://i.imgur.com/WyM2oxi.gifv But what I didn't expect to happen, was here, when you click the Left button to fire a new missile when the other missile is still in transit: https://i.imgur.com/PFJTDV1.gifv When the next missile is fired, the original missile changes course, re-angles itself and flies towards the next clicked spot, abandoning it's first clicked target, which is not what I wanted lol. It's like the missiles turn into smart missiles all of a sudden. The good news is that they're being destroyed when they hit the spot anyways, so that's something. So, for anyone reading this post, how can I make the previous missiles stay on their original target, even if I click the mouse to summon a new missile? Each missile's path should be independent of each other. This will also play into the logic for the upcoming falling Asteroid class I'll be adding, so solving this one for me will also allow me to make independent asteroids and I'm almost done the game! lol Here's the code: Game.h #ifndef GAME_H_ #define GAME_H_ // Preprocessors #include "SDL.h" #include "SDL_image.h" #include "SDL_ttf.h" #include "SDL_mixer.h" #include <iostream> #include <sstream> #include <stdio.h> #include <math.h> #include <cmath> #include <vector> // Inclusions for game objects #include "Cannon.h" #include "Missile.h" #include "Ground.h" #include "Silo.h" #define FPS_DELAY 500 #define SCREEN_WIDTH 800 #define SCREEN_HEIGHT 600 #define MAX_ROTATION 0 #define MIN_ROTATION 180 #define DEG_TO_RAD(deg) degrees * ( 3.141592653589793238 / 180) #define RAD_TO_DEG(rad) radians * ( 180 / 3.141592653589793238 ) #define OVER_PI ( 180 / 3.141592653589793238 ) class Game { public: Game(); ~Game(); bool Init(); void Run(); private: SDL_Window* window; SDL_Renderer* renderer; SDL_Texture* texture; // Timing unsigned int lastTick, fpsTick, fps, frameCount; // Test float testX, testY; /* Fonts for testing */ TTF_Font* fontMouseX; TTF_Font* fontMouseY; TTF_Font* fontCannonAngle; TTF_Font* fontFire; TTF_Font* fontAmmo; std::stringstream xValue; std::stringstream yValue; std::stringstream angleValue; std::stringstream fireValue; std::stringstream ammoValue; SDL_Texture* xTexture; SDL_Texture* yTexture; SDL_Texture* aTexture; SDL_Texture* fTexture; SDL_Texture* ammoTexture; int xWidth, xHeight, yWidth, yHeight, aWidth, aHeight; int fWidth, fHeight, ammoWidth, ammoHeight; /* END */ // Game objects Cannon* cannon; // The cannon, both the pipe and the base std::vector<Missile*> missileVec; // A vector of missiles Silo* silo; Ground* ground; // The ground SDL_Cursor* cursor; // The crosshair cursor // Flag to check if the cannon // is currently firing a missile bool isFiring; int clickedX; int clickedY; void Clean(); // Cleanup function void Update(float delta); // Update game elements void Render(float delta); // Render game elements void NewGame(); // Start a new game void SetCannonAngle( float vecX, float vecY); // Set the angle of cannon pipe double SetMissileAngle( float vecX, float vecY); // Set the angle of missile double ConvertDegrees(double radians); // Convert radians to degrees double ConvertRadians(double degrees); // Convert degrees to radians void ExplodeMissile(); // Explode the missile once it // has reached the target void CheckAsteroidCollisions(); // See if missile hits asteroid void CheckSiloCollisions(); // See if asteroid hits silo int GetSiloCount(); // Check if there are silos remaining }; #endif // GAME_H_ Game.cpp #include "Game.h" Game::Game() { window = 0; renderer = 0; } Game::~Game() { } bool Game::Init() { // Initialize the SDL video and audio subsystems SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO); // Create window window = SDL_CreateWindow("Missile Command v1.0", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL); if(!window) { std::cout << "Error creating window: " << SDL_GetError() << std::endl; return false; } // Create renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if(!renderer) { std::cout << "Error creating renderer: " << SDL_GetError() << std::endl; return false; } // Enable TTF loading TTF_Init(); // Load the fonts fontMouseX = TTF_OpenFont("lato.ttf", 14); fontMouseY = TTF_OpenFont("lato.ttf", 14); fontCannonAngle = TTF_OpenFont("lato.ttf", 14); fontFire = TTF_OpenFont("lato.ttf", 14); fontAmmo = TTF_OpenFont("lato.ttf", 14); // Initialize resources SDL_Surface* surface = IMG_Load("test.png"); texture = SDL_CreateTextureFromSurface(renderer,surface); SDL_FreeSurface(surface); // Set mouse cursor to crosshair cursor = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_CROSSHAIR); SDL_SetCursor(cursor); // Initialize timing lastTick = SDL_GetTicks(); fpsTick = lastTick; fps = 0; // Set starting FPS value frameCount = 0; // Set starting frame count testX = 0; testY = 0; return true; } void Game::Clean() { // Clean resources SDL_DestroyTexture(texture); SDL_FreeCursor(cursor); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); // Clean test data SDL_DestroyTexture(xTexture); SDL_DestroyTexture(yTexture); SDL_DestroyTexture(aTexture); SDL_DestroyTexture(fTexture); SDL_DestroyTexture(ammoTexture); } void Game::Run() { // Create game objects cannon = new Cannon(renderer); ground = new Ground(renderer); silo = new Silo(renderer); // Start a new game NewGame(); // Main loop while(1) { // Event handler SDL_Event e; // If event is a QUIT event, stop the program if(SDL_PollEvent(&e)) { if(e.type == SDL_QUIT) { break; } // If a mouse button was pressed... else if(e.type == SDL_MOUSEBUTTONDOWN) { // If the left mouse button was pressed, // set the "fire" flag to TRUE and // record x,y position of click if(e.button.button == SDL_BUTTON_LEFT) { clickedX = e.button.x; clickedY = e.button.y; isFiring = true; } } } // Calculate delta and fps unsigned int curTick = SDL_GetTicks(); float delta = (curTick - lastTick) / 1000.0f; // Cap FPS delay to specific amount if(curTick - fpsTick >= FPS_DELAY) { fps = frameCount * (1000.0f / (curTick - fpsTick)); fpsTick = curTick; frameCount = 0; //std::cout << "FPS: " << fps << std::endl; char buf[100]; snprintf(buf,100,"Missile Command v1.0 (fps: %u)", fps); SDL_SetWindowTitle(window,buf); } else { frameCount++; } lastTick = curTick; // Update and render the game Update(delta); Render(delta); } delete cannon; //missileVec.clear(); delete ground; delete silo; Clean(); // Close the fonts TTF_CloseFont(fontMouseX); TTF_CloseFont(fontMouseY); TTF_CloseFont(fontCannonAngle); TTF_CloseFont(fontFire); TTF_CloseFont(fontAmmo); TTF_Quit(); SDL_Quit(); } void Game::NewGame() { } void Game::Update(float delta) { // Game logic // Input, get mouse position to determine // the cannon pipe's angle for rendering int mX, mY; SDL_GetMouseState(&mX,&mY); // Assign the vector to variables float vectorX = mX - cannon->x; float vectorY = mY - cannon->y; // "Snap" the cannon angle to the angle between // cannon and mouse SetCannonAngle( vectorX, vectorY ); // If cannon is firing, create a missile and add // it to the missile vector container, and set // "isFiring" to false again if( isFiring == true ) { Missile* newMissile = new Missile(renderer, cannon->x, cannon->y); missileVec.push_back(newMissile); isFiring = false; } // If there are missiles in the vector container, set their direction // angle, fire them and update the missile positions for( int i = 0; i < missileVec.size(); i++ ) { // Update the missile's trajectory upon travel missileVec[i]->endX = clickedX; missileVec[i]->endY = clickedY; // Set a vector between the clicked location // and the missile float targetX = clickedX - missileVec[i]->x; float targetY = clickedY - missileVec[i]->y; // Set facing angle for missile missileVec[i]->angle = SetMissileAngle(targetX,targetY); // Update the missile's position missileVec[i]->Update(delta); // If the missile is triggered to be destroyed, // destroy it if( missileVec[i]->destroyNow == true ) { // Remove the destroyed missile // from the vector missileVec.pop_back(); } } /*// If there are no more silos, // start a new game if(GetSiloCount() == 0) { NewGame(); }*/ // Check if the cannon has fired a missile //cannon->missile->Update(delta, mX - cannon->x, mY - cannon->y); /* Test Data */ // Stream the X, Y, Angle and isFired values xValue.str(""); // Clear the stream before piping the xValue xValue << "X: " << mX; yValue.str(""); // Clear the stream before piping the yValue yValue << "Y: " << mY; angleValue.str(""); // Clear the stream before piping the angleValue angleValue << "Angle: " << cannon->angle; fireValue.str(""); // Clear the stream before piping the fireValue fireValue << "isFiring: " << std::boolalpha << isFiring; ammoValue.str(""); // Clear the stream before piping the ammoValue ammoValue << "Missiles in Vector: " << missileVec.size(); // Set font color to WHITE SDL_Color textColor = {255,255,255}; //*************************************** // DEBUG - Prepare the fonts for testing //*************************************** // Render the X-coordinate text SDL_Surface* temp = TTF_RenderText_Solid( fontMouseX, xValue.str().c_str(), textColor ); xTexture = SDL_CreateTextureFromSurface( renderer, temp ); xWidth = temp->w; xHeight = temp->h; SDL_FreeSurface(temp); // Render the Y-coordinate text temp = TTF_RenderText_Solid( fontMouseY, yValue.str().c_str(), textColor ); yTexture = SDL_CreateTextureFromSurface( renderer, temp ); yWidth = temp->w; yHeight = temp->h; SDL_FreeSurface(temp); // Render the angle text temp = TTF_RenderText_Solid( fontCannonAngle, angleValue.str().c_str(), textColor ); aTexture = SDL_CreateTextureFromSurface( renderer, temp ); aWidth = temp->w; aHeight = temp->h; SDL_FreeSurface(temp); // Render the isFiring text temp = TTF_RenderText_Solid( fontFire, fireValue.str().c_str(), textColor ); fTexture = SDL_CreateTextureFromSurface( renderer, temp ); fWidth = temp->w; fHeight = temp->h; SDL_FreeSurface(temp); // Render the missileVec.size() text temp = TTF_RenderText_Solid( fontAmmo, ammoValue.str().c_str(), textColor ); ammoTexture = SDL_CreateTextureFromSurface( renderer, temp ); ammoWidth = temp->w; ammoHeight = temp->h; SDL_FreeSurface(temp); } void Game::SetCannonAngle(float vecX, float vecY) { // "Snap" cannon angle to angle where mouse // cursor is located in order to track it double theAngle = atan2(vecY, vecX); // Pass radian angle to convert to degrees theAngle = ConvertDegrees(theAngle); // Convert degrees format from -180 to 180 // to 0 to 360 if( theAngle < 0 ) { theAngle = 360 - (-theAngle); } if(theAngle > MAX_ROTATION && theAngle < 90) { cannon->angle = MAX_ROTATION; } else if(theAngle < MIN_ROTATION && theAngle > 90) { cannon->angle = MIN_ROTATION; } else { cannon->angle = theAngle; } } double Game::SetMissileAngle(float vecX, float vecY) { // "Snap" missile angle to angle where mouse // cursor is located in order to track it double theAngle = atan2(vecY,vecX); // Pass radian angle to convert to degrees theAngle = ConvertDegrees(theAngle); // Convert degrees format from -180 to 180 // to 0 to 360 if( theAngle < 0 ) { theAngle = 360 - (-theAngle); } return theAngle; } double Game::ConvertDegrees(double radians) { // Convert the angle from radians to // degrees and return the value return RAD_TO_DEG(rad); } double Game::ConvertRadians(double degrees) { // Convert the angle from degrees to // radians and return the value return DEG_TO_RAD(deg); } int Game::GetSiloCount() { int siloCount = 0; // If the current silo is still alive, // the game is not over if(silo->state) { siloCount = 1; } return siloCount; } void Game::Render(float delta) { // Clear the renderer SDL_RenderClear(renderer); // Render the game objects cannon->Render(delta); ground->Render(delta); silo->Render(delta); // If there is a missile in the vector, // render it for( int i = 0; i < missileVec.size(); i++ ) { missileVec[i]->Render(delta); } /* Setting source rectangles and then rendering the x, y and angle fonts */ // For x SDL_Rect rect; rect.x = 20; rect.y = 20; rect.w = xWidth; rect.h = xHeight; SDL_RenderCopy(renderer, xTexture, 0, &rect); // For y rect.x = 20; rect.y = 40; rect.w = yWidth; rect.h = yHeight; SDL_RenderCopy(renderer, yTexture, 0, &rect); // For angle rect.x = 20; rect.y = 60; rect.w = aWidth; rect.h = aHeight; SDL_RenderCopy(renderer, aTexture, 0, &rect); // For isFired rect.x = 20; rect.y = 80; rect.w = fWidth; rect.h = fHeight; SDL_RenderCopy(renderer, fTexture, 0, &rect); // For isFired rect.x = 20; rect.y = 100; rect.w = ammoWidth; rect.h = ammoHeight; SDL_RenderCopy(renderer, ammoTexture, 0, &rect); // Present the renderer to display SDL_RenderPresent(renderer); } Missile.h #ifndef MISSILE_H_INCLUDED #define MISSILE_H_INCLUDED #include "Entity.h" #include <math.h> class Missile : public Entity { public: Missile(SDL_Renderer* renderer, float cX, float cY); ~Missile(); void Update(float delta); void Render(float delta); void Fire(); void Move(); // Starting and ending positions for missile float startX, startY, endX, endY; float directionX, directionY; float distance, speed; // The missile's angle double angle; // Flag to have missile destroyed // when certain conditions are met bool destroyNow; private: SDL_Texture* texture; // Texture for missile SDL_Point center; }; #endif // MISSILE_H_INCLUDED Missile.cpp #include "Missile.h" Missile::Missile(SDL_Renderer* renderer, float cX, float cY) : Entity(renderer) { // Create missile texture SDL_Surface* surface = IMG_Load("images/missile.png"); texture = SDL_CreateTextureFromSurface(renderer,surface); SDL_FreeSurface(surface); // Set angle variable default, // width, height angle = 0.0f; width = 34; height = 13; // Set missile offset for positioning relative to cannon float xOffset = 8; // Set starting x,y position x = cX + xOffset; y = cY; // Set the missile's starting x and y position // and speed startX = x; startY = y; speed = 150; // Set the missile's center for rotation center.x = ( width / 2 ); center.y = ( height / 2 ); // Set destruction flag to false destroyNow = false; } Missile::~Missile() { // Clean resources SDL_DestroyTexture(texture); } void Missile::Move() { // Determine the distance from the starting // position to the ending position distance = sqrt( pow(endX - startX, 2) + pow(endY - startY, 2)); // Determine direction of movement directionX = (endX - startX) / distance; directionY = (endY - startY) / distance; } void Missile::Update(float delta) { // Call move function Move(); // If the missile is moving, // update its position this->x += directionX * speed * delta; this->y += directionY * speed * delta; // If the missile goes BEYOND the // destination x and y (endX and endY), // set the missile's position to endX // and endY and stop movement if( sqrt( pow( this->x - startX, 2) + pow( this->y - startY, 2) ) >= distance ) { this->x = endX; this->y = endY; this->destroyNow = true; } } void Missile::Render(float delta) { // Render the missile SDL_Rect rect; rect.x = (int)(x + 0.5f); rect.y = (int)(y + 0.5f); rect.w = width; rect.h = height; // Render the missile at given angle SDL_RenderCopyEx(renderer,texture,0,&rect,angle,&center,SDL_FLIP_NONE); } I appreciate any feedback, guys. Thanks in advance. Also, let me know if you need more information about this post and I can provide it when I can.
  23. Hi, I am writing a Windows multithreaded SDL 1.2 application, and am trying to fix a performance bug by process of elimination (graphics thread only wakes up once every 5 seconds for now). The bug is that when I move the mouse in circles, everything is fine for the first 50 seconds (smooth mouse movement and low CPU usage), and then the CPU usage spikes and the mouse starts to lag and skip rather than move smoothly. I am taking mouse input in the input thread as follows: while (SDL_WaitEvent(g_pEventData)) { ... SDL_Delay(10);//this was the recommendation i saw when researching perf issues } Windows Performance Analyzer tells me theres a large amount of CPU usage taken by KernelBase.dll!SleepEx which I THINK is called internally from SDL_WaitEvent in the loop above. Does anyone have an idea why the CPU usage suddenly spikes and performance lags after 50 seconds although I'm making the same circular mouse movements the whole time? Thanks.
  24. I am trying to implement sprite clips, or rendering a portion of a sprite sheet onto the screen. For now, I am least trying to get one sprite to display on the screen. Controller support and adding the other sprites when changing the character direction will come later. Here is what I have so far. First, the class declaration: class World1 { public: //other stuff //screen resolution int window_width = 0; int window_height = 0; //handles player void renderPlayer(SDL_Renderer*&); //other stuff private: //player graphic and rectangle structs/variables/etc. SDL_Texture* pSpriteSheet = nullptr; SDL_Rect pSpriteClips[3]; SDL_Rect* pSprite; SDL_Rect pBase; SDL_RendererFlip sFlip = SDL_FLIP_NONE; //other stuff }; Then, the constructor: World1::World1(int SCREEN_WIDTH, int SCREEN_HEIGHT, SDL_Renderer*& renderer) { window_width = SCREEN_WIDTH; window_height = SCREEN_HEIGHT; *pSpriteSheet = IMG_LoadTexture(renderer, "male_base-test-anim.gif"); if (pSpriteSheet == nullptr) { cout << "Unable to load player Sprite sheet."; } //facing down sprite pSpriteClips[0].x = 14; pSpriteClips[0].y = 12; pSpriteClips[0].w = 145; pSpriteClips[0].h = 320; //more code... //player sprite pBase.x = 0; pBase.y = 0; pBase.w = pSpriteClips[0].w; pBase.h = pSpriteClips[0].h; } Then, the rendering void World1::renderPlayer(SDL_Renderer*& renderer) { //render SDL_RenderClear(renderer); //clears screen SDL_RenderCopyEx(renderer, pSpriteSheet, pSprite, &pBase, 0.0, NULL, sFlip); SDL_RenderPresent(renderer); //puts image on screen } So far, the program does not build and I obtain the following error: C:\Users\Kevin\Documents\Codeblocks\KnightQuest\worlds.cpp|12|error: invalid use of incomplete type 'SDL_Texture {aka struct SDL_Texture}'| Am I mistaken to assume that C++ will automatically assign a memory address to SDL_Rect* when I assign a value to it via the dereference operator? Or, perhaps there is another issue?
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!