Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I'm creating a shooter game in C++ with a spaceship in space, but I want to replace the rectangle bullets with my bullet.png, the file

I'm creating a shooter game in C++ with a spaceship in space, but I want to replace the rectangle bullets with my bullet.png, the file is already added to the resource files but i don't know what to change to replace the rectangle bullets with the bullet.png

Here is the code:

Main.cpp

#include  #include "Engine.h" int main(int argc, char* argv[]) // char** argv { Engine engine; return engine.Run(); }

Engine.cpp

#include "Engine.h" #include  #include  using namespace std; Engine::Engine():m_pWindow(nullptr), m_pRenderer(nullptr), m_isRunning(false) { // m_pWindow = nullptr; // Same as above. m_pShipTexture = nullptr; m_pBGTexture = nullptr; speed = 200; angle = 90.0; // You can do any of the above in the initializer list too. } int Engine::Run() { if (m_isRunning) { return 1; // 1 arbitrarily means that engine is already running. } if (Init("GAME1007_M1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, NULL)) { return 2; // 2 arbitrarily means that something went wrong in init. } while (m_isRunning) // Main game loop. Run while isRunning = true. { Wake(); HandleEvents(); // Input Update(); // Processing Render(); // Output if (m_isRunning == true) Sleep(); } Clean(); // Deinitialize SDL and free up memory. return 0; } int Engine::Init(const char* title, const int xPos, const int yPos, const int width, const int height, const int flags) { cout << "Initializing framework..." << endl; SDL_Init(SDL_INIT_EVERYTHING); m_pWindow = SDL_CreateWindow(title, xPos, yPos, width, height, flags); if (m_pWindow == nullptr) // Or NULL is okay too { cout << "Error during window creation!" << endl; return 1; } m_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0); if (m_pRenderer == nullptr) // Or NULL is okay too { cout << "Error during renderer creation!" << endl; return 1; } if (IMG_Init( IMG_INIT_PNG | IMG_INIT_JPG ) == 0) { cout << SDL_GetError() << endl; // Prints last SDL error msg. return 1; } m_pShipTexture = IMG_LoadTexture(m_pRenderer, "../Assets/img/ship.png"); m_pBGTexture = IMG_LoadTexture(m_pRenderer, "../Assets/img/background.png"); // Load bullet texture. // Since the textures are pointers, we can test to see if they're nullptr. m_fps = 1.0 / (double)FPS; // Converts FPS into a fraction of seconds. m_pKeystates = SDL_GetKeyboardState(nullptr); lastFrameTime = chrono::high_resolution_clock::now(); m_dstShip = {WIDTH/2.0f - 154.0f/2.0f, HEIGHT/2.0f - 221.0f/2.0f , 154.0f, 221.0f}; // x, y, w, h m_isRunning = true; // Start your engine. return 0; } void Engine::HandleEvents() { cout << "Handling events..." << endl; SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: // Pressing 'X' icon in SDL window. m_isRunning = false; // Tell Run() we're done. break; case SDL_KEYDOWN: if (event.key.keysym.scancode == SDL_SCANCODE_SPACE) { m_bulletVec.push_back( new Bullet( { m_dstShip.x + m_dstShip.w / 2, m_dstShip.y + m_dstShip.h / 2 }, 400.0) ); } else if (event.key.keysym.scancode == SDL_SCANCODE_X) // Prefer in a SDL_KEYUP { for (auto bullet : m_bulletVec) { delete bullet; // Deallocate bullet element. bullet = nullptr; // Resetting our dangling pointer. } m_bulletVec.clear(); // Clear all elements. size = 0 m_bulletVec.shrink_to_fit(); // Shrink capacity to size. capacity = 0 } break; } } } void Engine::Wake() { thisFrameTime = chrono::high_resolution_clock::now(); // New snapshot of number of seconds. lastFrameDuration = thisFrameTime - lastFrameTime; deltaTime = lastFrameDuration.count(); // Now we have our deltaTime multiplier. lastFrameTime = thisFrameTime; m_start = thisFrameTime; // Comment this out to just use deltaTime. } bool Engine::KeyDown(SDL_Scancode c) { if (m_pKeystates != nullptr) { if (m_pKeystates[c] == 1) return true; } return false; } void Engine::Update() { cout << "Updating frame..." << endl; string tickLabel = "DT: " + to_string(deltaTime); cout << "Bullets: " << m_bulletVec.size() << endl; SDL_SetWindowTitle(m_pWindow, tickLabel.c_str()); // c_str just returns the char array (char *) // Move ship. if (KeyDown(SDL_SCANCODE_W) && m_dstShip.y > 0) { m_dstShip.y -= speed * deltaTime; // speed per second, not per frame. } else if (KeyDown(SDL_SCANCODE_S)) { m_dstShip.y += speed * deltaTime; } if (KeyDown(SDL_SCANCODE_A) && m_dstShip.x > 0) { m_dstShip.x -= speed * deltaTime; } else if (KeyDown(SDL_SCANCODE_D)) { m_dstShip.x += speed * deltaTime; } //// Rotate ship. //if (KeyDown(SDL_SCANCODE_Q) || KeyDown(SDL_SCANCODE_LEFT)) //{ // angle -= 90 * deltaTime; //} //else if (KeyDown(SDL_SCANCODE_E) || KeyDown(SDL_SCANCODE_RIGHT)) //{ // angle += 90 * deltaTime; //} // Update all bullets. for (auto bullet : m_bulletVec) // For all elements of vector. { bullet->Update(deltaTime); // -> is the dot (.) operator for pointers. // if bullet's m_deleteMe is true, destroy bullet. } } void Engine::Sleep() { // Note: Not really better, but you can decide to not limit frameRate and just use deltaTime. // Comment all this out to just use deltaTime. m_end = chrono::high_resolution_clock::now(); m_diff = m_end - m_start; // Similar to before, but now chrono and double. if (m_diff.count() < m_fps) SDL_Delay((Uint32)((m_fps - m_diff.count()) * 1000.0)); // Sleep for number of ms. } void Engine::Render() { cout << "Rendering changes..." << endl; SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 0, 255); SDL_RenderClear(m_pRenderer); // Render the GameObjects. SDL_RenderCopy(m_pRenderer, m_pBGTexture, NULL, NULL); // All the pixels! // Render all the bullets. SDL_SetRenderDrawColor(m_pRenderer, 0, 0, 255, 255); for (auto bullet : m_bulletVec) // For all elements of vector. { SDL_RenderFillRectF(m_pRenderer, bullet->GetRect()); // SDL_RenderCopyExF(m_pRenderer, m_pShipTexture, NULL, bullet->GetRect(), 90, NULL, SDL_FLIP_NONE); // Get the hint? } SDL_RenderCopyExF(m_pRenderer, m_pShipTexture, NULL, &m_dstShip, angle, NULL, SDL_FLIP_NONE); SDL_RenderPresent(m_pRenderer); // Flips the buffers. } void Engine::Clean() { cout << "Cleaning up..." << endl; for (auto bullet : m_bulletVec) { delete bullet; // Deallocate bullet element. bullet = nullptr; // Resetting our dangling pointer. } m_bulletVec.clear(); // Clear all elements. size = 0 m_bulletVec.shrink_to_fit(); // Shrink capacity to size. capacity = 0 SDL_DestroyRenderer(m_pRenderer); SDL_DestroyWindow(m_pWindow); SDL_DestroyTexture(m_pShipTexture); SDL_DestroyTexture(m_pBGTexture); IMG_Quit(); SDL_Quit(); }

Bullet.cpp

#include "Bullet.h" Bullet::Bullet(const SDL_FPoint spawn, const double speed) { m_dst = { spawn.x - 16.0f, spawn.y - 32.0f, 32.0f, 64.0f}; // m_src = {x,y,w,h}; this->m_speed = speed; // this-> is a pointer to the object that invokes the function. // this-> is optional and rarely used. But could be. m_dx = 1.0; m_dy = 0.0; // No movement on Y axis. } void Bullet::Update(const double dt) { m_dst.x += m_dx * m_speed * dt; // m_dst.y += m_dy * m_speed * dt; // Check if bullet goes off-screen. If so, set m_deleteMe to true. } SDL_FRect* Bullet::GetRect() { return &m_dst; }

Engine.h

// #pragma once #ifndef __ENGINE_H__ #define __ENGINE_H__ #include  #include  #include  #include  #include "Bullet.h" using namespace std; #define WIDTH 1024 #define HEIGHT 768 #define FPS 120 class Engine { public: // Put public heading first so you ALWAYS question why things are public! Engine(); // What? What is this? int Run(); private: // For fixed timestep. chrono::time_point m_start, m_end; chrono::duration m_diff; double m_fps; // Changed to double. const Uint8* m_pKeystates; SDL_Window* m_pWindow; // Pointers are normal variables that hold addresses. SDL_Renderer* m_pRenderer; // Pointer to "back buffer" bool m_isRunning; vector m_bulletVec; // Vector of bullet addresses (pointers) // Example-specific properties. double speed, angle; SDL_Texture *m_pShipTexture, *m_pBGTexture; // Also a *m_pBulletTexture? SDL_Rect m_srcShip, m_srcBG, m_dstBG; SDL_FRect m_dstShip; // Floating-point precision. chrono::time_point lastFrameTime, thisFrameTime; // Cleaned this up. chrono::duration lastFrameDuration; double deltaTime; int Init(const char*, const int, const int, const int, const int, const int); void HandleEvents(); void Wake(); bool KeyDown(SDL_Scancode); void Update(); void Sleep(); void Render(); void Clean(); }; #endif

Bullet.h

#pragma once #include  class Bullet { public: Bullet(const SDL_FPoint spawn, const double speed); // Constructor. void Update(const double dt); // Bullet will move itself. // void Render(); // What info would this need from the Engine? SDL_FRect* GetRect(); // Getter. bool m_deleteMe; private: SDL_FRect m_dst; // SDL_Rect m_src; // To use ALL pixels from image make src NULL. double m_speed, m_dx, m_dy; };

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Dental Assisting

Authors: Doni Bird, Debbie Robinson

13th Edition

978-0323624855, 0323624855

Students also viewed these Programming questions

Question

What is marketing?

Answered: 1 week ago