Search the Community

Showing results for tags 'SDL'.



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

  • News

Categories

  • Audio
  • Visual Arts
  • Programming
  • Writing

Categories

  • Audio Jobs
  • Business Jobs
  • Game Design Jobs
  • Programming Jobs
  • Visual Arts Jobs

Categories

  • GameDev Unboxed

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
  • Topical
    • Virtual and Augmented Reality
    • News
  • Community
    • GameDev Challenges
    • For Beginners
    • 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
  • Workshops
    • C# Workshop
    • CPP Workshop
    • Freehand Drawing Workshop
    • Hands-On Interactive Game Development
    • SICP Workshop
    • XNA 4.0 Workshop
  • Archive
    • Topical
    • Affiliates
    • Contests
    • Technical

Calendars

  • Community Calendar
  • Games Industry Events
  • Game Jams

Blogs

There are no results to display.

There are no results to display.

Marker Groups

  • Members

Group


About Me


Website


Industry Role


Twitter


Github


Twitch


Steam

Found 27 results

  1. 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! [For Moderators]: I hope that's the best section to post such a post, I do apologize in advance if it's not the correct place.
  2. 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.
  3. 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:
  4. Docker for SDL gamedev

    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.
  5. 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(); }
  6. 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.
  7. 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
  8. 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.
  9. 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); } } }
  10. C++ Player out of tile map

    Hi! I made a tile map reading from a file. Almost everything works good, but when a player go out of map, program runs into an error and says that "vector subscript out of range". My question is how to make check for it Drawing map : void GameplayScreen::DrawMap(SDL_Renderer *renderer) { for (int y = map.size() - 1; y >= 0; --y) { for (int x = getStartBlockX(), xEnd = getEndBlockX(); x < xEnd && x < map[y].size(); ++x) { if (map[y][x] != "0,0") { int tempX = atoi(map[y][x].substr(0, map[y][x].find(',')).c_str()); int tempY = atoi(map[y][x].substr(map[y][x].find(',') + 1).c_str()); srcRect.x = tempX * 32; srcRect.y = tempY * 32; srcRect.w = 32; srcRect.h = 32; destRect.x = x * 32 + posX; destRect.y = (y * 32 + posY); destRect.w = 32; destRect.h = 32; vBlock[Earth]->Draw(renderer, srcRect, destRect); } } } } getStartBlockX returns first map block, getEndBlockX returns last, so it's like render on screen only a piece of map, not all blocks. tempX returns x coordinate of tile image, tempY y coordinate. So, for example, if map is like : 0,0 0,0 0,0 0,0 0,0 0,0 0,0 0,0 0,0 0,0 1,0 2,0 0,3 1,0 1,0 0,0 is first block image, 1,0 is one next to the first, 0,3 is 2 under the first block etc.
  11. 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; } } } }
  12. Hi I'm new to learning OpenGL and still learning C. I'm using SDL2, glew, OpenGL 3.3, linmath and stb_image. I started following through learnopengl.com and got through it until I had to load models. The problem is, it uses Assimp for loading models. Assimp is C++ and uses things I don't want in my program (boost for example) and C support doesn't seem that good. Things like glVertexAttribPointer and shaders are still confusing to me, but I have to start somewhere right? I can't seem to find any good loading/rendering tutorials or source code that is simple to use and easy to understand. I have tried this for over a week by myself, searching for solutions but so far no luck. With tinyobjloader-c and project that uses it, FantasyGolfSimulator, I was able to actually load the model with plain color (always the same color no matter what I do) on screen and move it around, but cannot figure out how to use textures or use its multiple textures with it. I don't ask much: I just want to load models with textures in them, maybe have lights affect them (directional spotlight etc). Also, some models have multiple parts and multiple textures in them, how can I handle those? Are there solutions anywhere? Thank you for your time. Sorry if this is a bit confusing, English isn't my native language
  13. 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.
  14. How do I Script NPC's? (C++)

    I've been wanting to figure out a proper method to script NPC's for my game engine. The NPC object class contains simple methods to draw, update, and move the character (Other methods for dialogue will be added on later). The problem is that, of course, they don't do anything. These characters need some sort of script. But I can't figure out anyway I can each assign these to each NPC. By scripting, I mean something that would look like this. A file that I could assign each NPC so that they follow the script. moveWest(3); // Move in the west direction for 3 tiles followPlayer(); // Start following the player speak("Hello there!") // Talk to the player It won't look exactly like that, but that's something similar to what I want to accomplish here. I know there are some methods out there, but I need a proper method that I could use for my situation. I don't know how useful this information is going to be, but I want to make it clear that my NPC's update function is updated based on frames. Basically, the function runs 60 times every second, the speed that my game engine is also running at. If any other additional information is needed, let me know. I appreciate any help with this.
  15. ¡ 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
  16. Hello, my name is Mark. I'm hobby programmer. So recently,I thought that it's good idea to find people to create a full 3D engine. I'm looking for people experienced in scripting 3D shaders and implementing physics into engine(game)(we are going to use the React physics engine). And,ye,no money =D I'm just looking for hobbyists that will be proud of their work. If engine(or game) will have financial succes,well,then maybe =D Sorry for late replies. I mostly give more information when people PM me,but this post is REALLY short,even for me =D So here's few more points: Engine will use openGL and SDL for graphics. It will use React3D physics library for physics simulation. Engine(most probably,atleast for the first part) won't have graphical fron-end,it will be a framework . I think final engine should be enough to set up an FPS in a couple of minutes. A bit about my self: I've been programming for 7 years total. I learned very slowly it as "secondary interesting thing" for like 3 years, but then began to script more seriously. My primary language is C++,which we are going to use for the engine. Yes,I did 3D graphics with physics simulation before. No, my portfolio isn't very impressive. I'm working on that No,I wasn't employed officially. If anybody need to know more PM me.
  17. I've seen some SDL tutorials on implementing side-scrolling, and I don't understand how they do it. All of the tutorials I've seen do it like this:(taken from LazyFoo's code) camera.x = ( dot.getPosX() + Dot::DOT_WIDTH / 2 ) - SCREEN_WIDTH / 2; camera.y = ( dot.getPosY() + Dot::DOT_HEIGHT / 2 ) - SCREEN_HEIGHT / 2; This part, I at least understand. The camera's position is the position of the dot's origin minus the screen's width or height, because the camera should start moving should the dot's x or y coordinates exceed the middle of the screen. The part which I absolutely don't understand is this: void Dot::render( int camX, int camY ) { gDotTexture.render( mPosX - camX, mPosY - camY ); } In the above code, where the dot is drawn on the screen is the dot's x and y coordinates subtracted by the camera's x and y coordinates. I don't understand how or why one would come to the conclusion that the dot is to be rendered at the coordinates. I don't understand how it works. Can someone please explain?
  18. Hi there, I posted this to be resolved in SDL forums so Im gonna left here the link to original discussion https://discourse.libsdl.org/t/sdl-gl-swapwindow-is-not-working-for-me/22863 I don't want duplicate posts but I want reach the most people I be able to. Tell me If you think this is bad habits so I won't do again in advance. Thanks!
  19. Help with Missile Command

    Hello everyone. I'm fairly new to game programming and I've started the beginner's path to learning how to do game programming incrementally, as suggested by Alpha_ProgDes (hope I spelled his name right) in his fantastic article about Game Programming for Beginners and the 10 requisite games that you absolutely need to know and finish in order to get real game programming experience. After about 4 or so months of trial and error and growing pains, I was able to complete a working (but not perfect with lots of bad practice, global variables, etc.) copy of Pong, Snakes and Breakout. Right now I'm just doing enough to get the games to work (passable) and then later, I will go and re-do them after getting better at this. Currently, I'm on the fourth game of this list, which is Missile Command, and I'm only a little bit into the game and I'm now stuck on the first 'logic' aspect of just getting the cannon to rotate and change angle based on the position of the mouse. No matter what I've tried, I just can't seem to get the cannon to angle properly as per the precise location of the mouse. When I run the game, the cannon will move arbitrarily towards the right side, but never turn and angle to the left, even if my mouse is on the left-hand side of the game screen. I've created some test output for the x and y coordinate of the mouse position as well as the cannon's angle but it hasn't helped me that much yet. If it is allowed in these forums, I can record a small video that shows the output and paste it here as a link. But I'm not sure. Here is my code for main as well as the Game, Vector2 and Cannon classes (I have other classes but I told myself I would only work on them once I've solved this particular logic problem): main.h #ifndef MAIN_H_ #define MAIN_H_ #include "game.h" int main(int argc, char* argv[]); #endif // MAIN_H_ main.cpp //****************************************** // Missile Command - v1.0.0 // By: Pedro Miranda Jr. (Glydion) // // Start Date: Wednesday May 31, 2017 // Finish Date: //****************************************** #include "main.h" int main(int argc, char* argv[]) { // Create the game object Game* game = new Game(); // Initialize and run the game if(game->Init()) { game->Run(); } // Clean up delete game; return 0; } Vector2.h #ifndef VECTOR2_H_INCLUDED #define VECTOR2_H_INCLUDED #include <math.h> class Vector2 { public: Vector2(); Vector2(float x, float y); ~Vector2(); float x, y; }; #endif // VECTOR2_H_INCLUDED Vector2.cpp #include "Vector2.h" Vector2::Vector2() { } Vector2::Vector2(float x, float y) { this->x = x; this->y = y; } Vector2::~Vector2() { } Cannon.h #ifndef CANNON_H_INCLUDED #define CANNON_H_INCLUDED #include "Entity.h" #include <math.h> // Define a missile speed in pixels per second /*const float MISSILE_SPEED = 550; class Missile : public Entity { public: Missile(SDL_Renderer* renderer); ~Missile(); void Update(float delta); void Render(float delta); void SetDirection(float dirX, float dirY); float dirX, dirY; bool state; // Check if the missile is alive private: SDL_Texture* texture; }; */ class Cannon : public Entity { public: Cannon(SDL_Renderer* renderer); ~Cannon(); // x, y, width and height for base piece float baseX, baseY, baseWidth, baseHeight; // cannon pipe angle double angle; // Missiles that the cannon fires //Missile missile; // Fire a missile //void FireMissile(); void Update(float delta); void Render(float delta); float GetCenterX(); float GetCenterY(); private: SDL_Texture* cannonTexture; // Texture for cannon pipe SDL_Texture* baseTexture; // Texture for cannon base SDL_Point center; }; #endif // CANNON_H_INCLUDED Cannon.cpp #include "Cannon.h" //****************************** // Missile function definitions //****************************** //****************************** // Cannon function definitions //****************************** Cannon::Cannon(SDL_Renderer* renderer) : Entity(renderer) { // Create cannon pipe texture SDL_Surface* surface = IMG_Load("images/cannon-top.png"); cannonTexture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); // Create cannon base texture surface = IMG_Load("images/cannon-base.png"); baseTexture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); // Set the cannon pipe's dimensions width = 32; height = 48; // Set the cannon base's dimensions baseWidth = 64; baseHeight = 24; // Set the cannon pipe's vertical position x = 417 - width; y = 505; // Set the cannon base's vertical position baseX = 432 - baseWidth; baseY = 545; // Set the cannon pipe's rotation pivot point center.x = (width / 2); center.y = height; // Set the cannon pipe's angle angle = 0.0f; } Cannon::~Cannon() { // Clean resources SDL_DestroyTexture(cannonTexture); SDL_DestroyTexture(baseTexture); } void Cannon::Update(float delta) { } void Cannon::Render(float delta) { // Set source rectangle for cannon pipe SDL_Rect rect; rect.x = (int)(x + 0.5f); rect.y = (int)(y + 0.5f); rect.w = width; rect.h = height; // Render the cannon pipe SDL_RenderCopyEx(renderer,cannonTexture,0,&rect,angle,&center,SDL_FLIP_NONE); // Set source rectangle for cannon base rect.x = (int)(baseX + 0.5f); rect.y = (int)(baseY + 0.5f); rect.w = baseWidth; rect.h = baseHeight; // Render the cannon base SDL_RenderCopy(renderer,baseTexture,0,&rect); } float Cannon::GetCenterX() { return center.x; } float Cannon::GetCenterY() { return center.y; } 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> // Inclusions for game objects #include "Cannon.h" #include "Vector2.h" #include "Ground.h" #include "Silo.h" #define FPS_DELAY 500 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; std::stringstream xValue; std::stringstream yValue; std::stringstream angleValue; SDL_Texture* xTexture; SDL_Texture* yTexture; SDL_Texture* aTexture; int xWidth, xHeight, yWidth, yHeight, aWidth, aHeight; /* END */ // Game objects Cannon* cannon; // The cannon, both the pipe and the base Silo* silo; Ground* ground; // The ground SDL_Cursor* cursor; // The crosshair cursor Vector2* target; // The vector of the cursor void Clean(); // Cleanup function void Update(float delta); // Update game elements void Render(float delta); // Render game elements void NewGame(); // Start a new game double ConvertDegrees(double radians); // Convert radians to degrees void SetCannonAngle(Vector2* theVector); // Set the angle of the cannon pipe 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); // 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); } 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; } } // 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; delete ground; delete silo; Clean(); // Close the fonts TTF_CloseFont(fontMouseX); TTF_CloseFont(fontMouseY); TTF_CloseFont(fontCannonAngle); 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); // Create the target vector, normalize it // and pass it to the cannon to set the // current angle target = new Vector2(mX,mY); SetCannonAngle( target ); // If there are no more silos, // start a new game if(GetSiloCount() == 0) { NewGame(); } // Update the cannon's angle cannon->Update(delta); /* Test Data */ // Stream the X, Y and Angle 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; // Set font color to WHITE SDL_Color textColor = {255,255,255}; //*************************************** // DEBUG - Prepare the fonts for testing //*************************************** // Render the X-coordinate 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 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 temp = TTF_RenderText_Solid( fontCannonAngle, angleValue.str().c_str(), textColor ); aTexture = SDL_CreateTextureFromSurface( renderer, temp ); aWidth = temp->w; aHeight = temp->h; SDL_FreeSurface(temp); } void Game::SetCannonAngle( Vector2* theVector ) { // Calculate arc tangent between the // the mouse's position and the center // axis of the cannon and convert to degrees double theAngle = atan2( theVector->x, theVector->y ); theAngle = ConvertDegrees(theAngle); cannon->angle = theAngle; } double Game::ConvertDegrees(double radians) { // Convert the angle from radians to // degrees and return the value return radians * ( 180 / 3.141592653589793238 ); } 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); /* 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); // Present the renderer to display SDL_RenderPresent(renderer); } That's the code. Attached to this post is a set of stills that show that the cannon is not angling properly towards the crosshair cursor, either on the left side or the right side of the video screen. Any help would be appreciated, folks. Thank you for your time.
  20. 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.
  21. I am attempting to make a Pong game using SDL. I'm trying to render text on the screen, but segfaults prevent the code from running. I ran it in gdb, and found that the segfaults occur because SDL_QueryTexture doesn't give the ints passed into it any values. I put a statement to print SDL_GetError() after SDL_QueryTexture, and it says: "Failed loading SHCORE.DLL: The specified module could not be found." This wasn't happening after I made some adjustments to my code, so I believe the code is causing this problem. The relevant code is below: In case the rest of the code has a part in this, the entire .cpp file is attached. void loadText(string s) { SDL_Color color = {255,255,255}; SDL_Surface* textsurface = TTF_RenderText_Solid(font, s.c_str(), color); if(textsurface == NULL) { cout << "Could not rendertext onto surface" << endl; } texture = SDL_CreateTextureFromSurface(r,textsurface); if(texture == NULL) { cout << "Could not make texture" << SDL_GetError() << endl; } SDL_QueryTexture(texture, NULL, NULL, w, h); cout << SDL_GetError() << endl; SDL_FreeSurface(textsurface); textsurface = NULL; //cout << "Texture query error" << SDL_GetError() << endl; } void textRender(int x, int y) { destinationrect = {x,y,*w,*h}; if (SDL_RenderCopy(r,texture,NULL,&destinationrect) < 0) { cout << "Rendercopy error" << SDL_GetError() << endl; } } test.cpp OpenSans-Regular.ttf
  22. Blend Mode in SDL

    What is the Blend Mode in SDL and explains each mode such as SDL_BLENDMODE_BLEND, help me!!!
  23. Tetris Clone Code Review Request

    Hello! I have made a clone of Tetris using SDL libraries for C++. I would love to get some input as to what I have done right and wrong. Also please tell me if im using Github correctly, it confuses me greatly. (I tried to add a new commit to remove the misplaced header file "DungeonCrawlV4.o" but it doesn't seem to have taken place.) https://github.com/Starfruit64/Tetris-Clone
  24. I'm developing an android game and have been primarily using a PC build (on windows) with the Mali OpenGL ES 2.0 emulator, with a secondary Android Studio build for the devices. For various reasons I'm trying to change over to Linux, and I have Linux Mint on a new PC, and so I'm trying to get a similar PC build working under linux, however I am an absolute beginner at linux. It seems that a sensible option might be to use SDL on linux for stuff like creating a window, keyboard input etc. I gather that SDL2 is just the most up to date version of SDL, so I have been installing that with apt-get. However, when I try and install the Mali OpenGL ES emulator from ARM, I am getting a conflict: installed package 'libegl1-mesa-dev' conflicts with the installed package 'libgles2-mesa-dev' I am guessing this means that both SDL2 and Mali have some egl functionality, and they are treading on each others toes? There is some mention of this in the Mali help file: Is this --force-all option what I should do? Or is there no way to get SDL2 and Mali to play together? If not SDL2 then how should I be using Mali under linux (i.e. what other API should I be talking to for creating a window, keyboard input etc?)?
  25. 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?