Udemy
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
Turn what you know into an opportunity and reach millions around the world.
Learn More
Your cart is empty.
Keep shopping
Cyber Monday SDL3 Action RPG in C++
Rating: 3.1 out of 5(6 ratings)
191 students

Cyber Monday SDL3 Action RPG in C++

Learn Play and Discover Computer Science
Created byDion Jackson
Last updated 9/2025
English
English [Auto],

What you'll learn

  • The Simple Directmedia Layer 3 is new but easy to learn for creating unqiue looking proffesional applications for all your software development needs.
  • The following course contains active links and offical documenatation with source code and legible document font.
  • Make a fun action RPG with minimal effort using the C++ Language.
  • Students will learn how to create a game using the SDL3 system and how to add assets such as images and sound effects and music to the game.

Course content

3 sections203 lectures41h 36m total length
  • SDL3 Official Release3:26

    I hope you are excited about learning about using the Simple Directmedia Layer 3.  This new release has all of the feature once talked about in SDL2 now with webcam access, GPU support and more.

  • SDL3 Class Course Overview22:32

    Description of the many projects an activity lessons in the game development course using SDL3.

  • Display Resolutions7:44

    The resolution of a desktop refers to the number of pixels that can be displayed on the monitor's screen, typically expressed as width x height (e.g., 1920 x 1080). Common desktop resolutions include 1920x1080 (Full HD), 2560x1440 (QHD), and 3840x2160 (4K UHD).

    Understanding Resolution:


    • Pixels:

      Resolution is determined by the number of individual pixels that make up the image on the screen.


    • Width x Height:

      A resolution like 1920x1080 means the screen has 1920 pixels horizontally and 1080 pixels vertically.


    • Sharpness and Detail:

      Higher resolutions (more pixels) generally result in sharper, more detailed images.


    • Workspace:

      Higher resolutions also allow for more content to be displayed on the screen at once.


    Common Desktop Resolutions:

    • 1920x1080 (Full HD/1080p):

      The most common resolution, offering a good balance of image quality and performance.


    • 2560x1440 (QHD/1440p):

      Provides sharper images than 1080p, often used for gaming and content creation.


    • 3840x2160 (4K UHD):

      Offers the highest level of detail and clarity, ideal for professional applications like video editing and graphic design.


    • 1366x768:

      A lower resolution, often found on budget laptops and older displays.


    • 7680x4320 (8K UHD):

      A very high resolution, still relatively new and not as widely adopted as 4K.


    How to Check Your Screen Resolution:

    1. 1. Windows:

      Right-click on the desktop, select "Display settings," and find the "Display resolution" setting.


    2. 2. Mac:

      Open "System Settings," click "Displays," and hover over the display to see its resolution.


    3. 3. Chromebook:

      Click the clock, click the gear icon, and go to "Device" > "Display" to find the resolution.


  • C++ Advanced Topics36:20

    Graphics

    • SDL GPU API: This API provides cross-platform access to modern graphics hardware, including 3D graphics and compute support, akin to Vulkan, Direct3D 12, and Metal. It allows for greater control over the rendering pipeline compared to the simpler SDL Renderer API. You can utilize it for tasks like:

      • Creating and managing GPU resources: Shaders, vertex buffers, textures, and samplers.

      • Implementing advanced rendering techniques: Such as compute shaders for specialized effects or optimizations.

      • Optimizing rendering performance: By minimizing state changes, batching commands, and utilizing culling techniques.

    • Shaders: Learn to write custom shaders (vertex, fragment, and compute) to create sophisticated visual effects and achieve specific rendering goals.

    • Sprite Batching: Efficiently draw a large number of sprites using a single draw call, improving rendering performance.

    • Colorspace Support: Manage and utilize different color spaces within your application for improved color accuracy and HDR capabilities.

    • Hardware Video Decoding: Leverage the new renderer and texture properties to achieve hardware accelerated video decoding with full HDR support.


    Audio

    • Audio Streams: Manage multiple independent audio streams within your application, allowing different components to have their own audio devices and callbacks. This provides greater flexibility and power for complex audio setups.

    • Custom Audio Processing: Implement custom audio effects and manipulations by providing callbacks for individual audio streams.

    • Default Audio Device Management: SDL3 automatically handles device hotplugging, ensuring your application can adapt to changes in audio hardware configuration.


    Input

    • Better Keyboard Input: Explore enhanced keyboard input handling capabilities for more precise and responsive control.

    • Customizable Virtual Keyboards: Implement and customize virtual keyboards for mobile platforms like iOS and Android.

    • Pen API: Access and utilize pen input devices like Wacom tablets and Apple Pencil for creative applications.


    Other advanced topics

    • Multi-threading: SDL3 provides thread management functions, including thread creation, priority setting, and thread local storage. However, care must be taken to manage concurrency and ensure data integrity when working with multiple threads. Most SDL video functions are not thread-safe, so they should only be called from the main thread.

    • Process API: Spawn and manage child processes and communicate with them for enhanced application functionality.

    • App Metadata API: Provide SDL with information about your application for correct display in system dialogs (e.g., "About" dialogs on macOS).

    • Properties API: Utilize the fast and flexible dictionary-like Properties API for storing and retrieving name/value pairs.

    • Filesystem and Storage APIs: Explore the APIs for managing directories, accessing topic-specific user folders, and utilizing platform-specific storage.

    • Camera API: Access and utilize webcams for capturing video or still images within your application.

    • Main Callbacks: Optionally run your program from callbacks instead of the standard main() function.


  • SDL3 Makefile2:19

    Cmake like system required to use a makefile.

  • SDL3 VS Code Install6:58

    Lets look at some documentation of how to install SDL3 in the Visual Studio Code compiler program.

  • Modern OpenGL and SDL32:06:18

    Learn how to Create a Basic 2D or 3D game engine construct using the Simple Directmedia Layer 3.

  • Additional OpenGL Help58:41

    Overview of other actual operation performed using Modern OpenGL and SDL.

  • Vulkan and SDL319:42

    If you are changing rendering option some information included about using Vulkan and SDL3.

  • Vulkan SDL3 Physical Device9:46

    SDL3 offers support for Vulkan, and while it simplifies some aspects of Vulkan integration, the selection and management of the Vulkan physical device largely remain within the domain of the Vulkan API itself, not SDL.

    Here's how SDL3 and Vulkan physical devices interact:

    • SDL_GPU and Automatic Device Selection:


    1. If using SDL_GPU, SDL's higher-level rendering API, it attempts to automatically select the most suitable physical device based on initialization parameters. By default, it prefers dedicated GPUs over integrated ones unless SDL_PROP_GPU_DEVICE_CREATE_PREFERLOWPOWER_BOOLEAN is set to true during device creation.

    2. Direct Vulkan Integration:


    3. When directly using Vulkan with SDL3, SDL provides functions primarily for surface creation and instance extensions, such as SDL_Vulkan_CreateSurface() and SDL_Vulkan_GetInstanceExtensions().

    4. Vulkan's Role in Device Handling:


    5. The core logic for enumerating, selecting, and managing Vulkan physical devices (e.g., vkEnumeratePhysicalDevices, vkGetPhysicalDeviceProperties, vkGetPhysicalDeviceFeatures) is handled directly by the Vulkan API. SDL3 does not abstract or replace these Vulkan functions. You would still implement this device selection logic in your application code, using the Vulkan API, before proceeding to create a logical device and render to the SDL window's Vulkan surface.

    6. Device Feature Requirements:


    When creating a Vulkan-based SDL_GPU renderer or when directly using Vulkan, ensure the selected physical device meets the necessary Vulkan feature requirements, especially for cross-platform compatibility (e.g., Android).Missing required features can cause device creation to fail.

  • Vulkan Swapchain SDL35:45

    Key aspects of Vulkan Swapchain with SDL3:

    • Instance Extensions:

      SDL3 assists in obtaining the necessary platform-specific Vulkan instance extensions required for creating a VkInstance compatible with the SDL windowing system. This is typically done using SDL_Vulkan_GetInstanceExtensions().

    • Swapchain Creation and Management:

      • Vulkan applications explicitly create and manage the swapchain, which is a queue of images used for presentation to the screen.

      • SDL3's SDL_GPU API, which provides a higher-level abstraction over various graphics backends including Vulkan, can handle the underlying swapchain management when rendering to an SDL window.

      • When using the SDL_GPU API, rendering can target either textures (render targets) or directly the swapchain for presentation.

    • Swapchain Composition:

      SDL3 allows querying and potentially changing the swapchain composition (e.g., SDR, SDR\_LINEAR, HDR\_EXTENDED\_LINEAR, HDR10\_ST2084) using SDL_WindowSupportsGPUSwapchainComposition and related functions. This enables applications to leverage advanced display capabilities like HDR.

    • Window Resizing:

      When an SDL window is resized, the Vulkan swapchain typically needs to be recreated to match the new dimensions. SDL3's SDL_GPU backend handles this process, which involves stalling the GPU and flushing work before recreating the swapchain.


    In essence, while Vulkan's swapchain is a core component that requires explicit handling in a pure Vulkan application, SDL3 provides utilities and abstractions (especially through its SDL_GPU API) that streamline its integration and management within an SDL-based application, making it easier to set up and handle dynamic events like window resizing.

  • Our 3D Game Engine Project8:06


    1. Window and Renderer:

    SDL3 handles window creation and management, and provides access to a renderer (e.g., OpenGL, Vulkan) to display graphics on the screen.


    2. Input Handling:

    SDL3 captures input from various devices like keyboard, mouse, and gamepad, enabling player interaction.


    3. Audio:

    SDL3 manages audio playback, allowing for sound effects and background music.


    4. Game Logic:

    This includes the core mechanics of the game, such as movement, collision detection, and game state management.


    5. 3D Models and Scenes:

    SDL3 can work with 3D models loaded from files (e.g., .obj, .glb) and render them within the game world using the chosen rendering API.


    6. Camera:

    A camera object defines the player's view of the 3D world, including its position and orientation.


    7. Shaders:

    Shaders, often written in GLSL, are used to customize the appearance of 3D objects, including lighting and materials.


    SDL3's Role:

    • SDL3 provides the low-level infrastructure for handling windowing, input, and rendering, allowing developers to focus on game-specific logic.


    • It acts as a bridge between the game code and the underlying operating system and graphics hardware.


    • By utilizing SDL3, developers can write code once and have it run on multiple platforms (Windows, macOS, Linux, etc.).

  • SDL3 CodeBlocks Install Windows7:08

    To install SDL3 in the Code::Blocks compiler for windows download the MingGW files and SDL3 is the first step. The second step is to create a project  and place the SDL3.dll file in the main.cpp area of your project folder. The third step would be be then under the search directory of the project add the lib and include folders for SDL3 from MingGW. The fourth step would be to tell the compiler about SDL3 in the Linker Settings and add under other linker settings add the -lSDL3.dl1l and apply the settings.

  • Defining an Entry Point using OOP8:32
    1. SDL_main.h inclusion: To properly handle the entry point across various platforms, your main source file should include <SDL3/SDL_main.h>.

    2. Macro redefinition: This header might redefine main to SDL_main and inject platform-specific startup code to ensure consistent behavior regardless of the operating system.

    3. Internal handling: SDL then provides its own main function, or equivalent, that takes care of platform-specific argument parsing and initialization before calling your actual SDL_main (which was originally your main).

    4. ABI compatibility: While SDL3 aims for a stable ABI for its own functions, the specific implementation of the entry point might involve internal mechanisms that are not part of the public ABI, and therefore not directly exposed or meant for application interaction.

    5. Customizing the entry point: If you need to manage the entry point explicitly (for instance, if you are integrating SDL into a larger framework), you can #define SDL_MAIN_HANDLED before including SDL_main.h. In such cases, you would be responsible for calling SDL_SetMainReady() before initializing SDL and manually handling platform-specific startup procedures.

  • User Input with the Mouse and Keyboard10:58

    SDL3 provides robust mouse and keyboard input handling. Applications can retrieve mouse coordinates, button states, and keyboard key presses using event handling. For mouse input, SDL_GetMouseState() retrieves the current state, while SDL_EVENT_MOUSE_MOTION, SDL_EVENT_MOUSE_BUTTON_DOWN, etc., provide event-driven information. Keyboard input is similarly accessed via events like SDL_EVENT_KEY_DOWN and SDL_EVENT_KEY_UP, with the SDL_KeyboardEvent structure containing details like the key's scancode and keycode.

    Mouse Input:


    • SDL_GetMouseState: Retrieves the current mouse position and button states.


    • SDL_EVENT_MOUSE_MOTION: Triggered when the mouse is moved.


    • SDL_EVENT_MOUSE_BUTTON_DOWN/UP: Triggered when a mouse button is pressed or released.


    • SDL_SetWindowRelativeMouseMode: Hides the cursor, grabs mouse input to the window, and allows for unlimited mouse movement within the window.


    • SDL_CaptureMouse: Enables the application to obtain mouse events globally, not just within the window.

  • SDL3 Frames Per Second Game Loop8:58

    You need to regulate the FPS in order to avoid conditions such as screen tearing and a game running too fast on newer hardware in the future.

  • Free Development Tools and Services55:31

    For free game design and development, a range of excellent tools and services are available, from game engines to 3D modeling and art tools, as well as asset repositories. Popular choices include Unity, Unreal Engine, Godot, GameMaker, and Blender, among others. These tools offer features for visual scripting, 2D and 3D development, and asset creation, making game development accessible to everyone from beginners to experienced professionals

  • SDL3 Category API Wiki43:40
    1. CategoryFilesystem:

      Covers functions for examining and manipulating the system's filesystem, including paths, directories, and file information.

    2. CategoryThread:

      Deals with cross-platform thread management, including thread creation, priority, termination, and Thread Local Storage.

    3. CategoryStorage:

      Provides a high-level API to abstract portability issues related to storage access, particularly on platforms with stricter storage models.

    4. CategoryTimer:

      Includes functions for time management, measuring elapsed time, delaying execution, and setting up timers.

    5. CategoryVideo:

      Focuses on window management, OpenGL context creation, and rendering within SDL windows.

    6. CategoryLog:

      Manages logging messages with different priorities and categories for debugging and information purposes.

    7. CategoryGPU:

      Offers support for modern 3D graphics and compute functionalities, similar to Metal, Vulkan, and Direct3D 12.

    8. CategoryJoystick:

      Handles joystick and game controller management, including device identification, input handling, and virtual joysticks.

  • Game Programming Course53:27

    Game Development is not an art competition. The Simple Directmedia Layer 3 has much potential for cross-platform software development. Lets learn how to use SDL3 together.

  • Game Mechanics15:30

    Action RPGs combine the character progression and storytelling of role-playing games with the real-time combat and player-driven action of action games. Key mechanics include character customization and progression, real-time combat systems, gear and item management, and often, open-world exploration

  • SDL3 GPU1:12:53
  • SDL3 GPU Polygon1:03:00

    Learn to render 2d and 3d graphics with SDL3, creating a window and a renderer. Use GPU buffers and textures, and apply vertex and fragment shaders.

  • Runtime Polymorphism and the Renderer23:46

    Learn to use runtime polymorphism and templates to build a cross-platform renderer with OpenGL, Vulkan, or Metal backends. Utilize virtual functions and vtables to create reusable rendering code.

  • SDL3 Action RPG Concept24:49

    An action RPG (ARPG) is a video game genre that combines the real-time, action-oriented gameplay of action games with the character progression, stats, and story elements typically found in role-playing games (RPGs). Key features include direct control over characters, reflex-based combat, and a focus on character development through stats and equipment.

  • SDL3 Animate Image9:31

    Animating images in SDL3, often referred to as sprite animation, involves displaying a sequence of images (frames) quickly to create the illusion of movement.

  • SDL3 New ABI27:51

    SDL_AppQuit

    SDL_AppEvent

    SDL_AppInit

    SDL_AppInterate

    SDL_AppResult

  • Free Resources12:37

    Free assets for a game project and other free tools to help you to become more productive.

  • Project Assets16:02

    Some Suggestions of where to find project Assets on the web.

  • Platformer Engine Concept1:35:54

    Core Components of a C++ Platformer Jump:

    • Player State Management:

      • A boolean variable (e.g., isJumping, isGrounded) tracks the player's current state.

      • This state determines whether a jump can be initiated or if the player is currently in the air.

    • Input Handling:

      • Detect when the jump button (e.g., spacebar) is pressed.

      • This input triggers the jump action when the player is on the ground.

    • Vertical Velocity Manipulation:

      • Upon jumping, apply an upward force or impulse to the player's vertical velocity.

      • Gravity constantly pulls the player downwards, decreasing upward velocity and eventually causing descent.

      • This can be achieved by modifying the player's y coordinate based on velocity and delta time (for frame-rate independent movement).

    • Collision Detection:

      • Regularly check for collisions between the player and the ground or platforms.

      • When a collision with the ground is detected, reset the isJumping flag and potentially reset vertical velocity to zero to prevent sinking.


    Advanced Considerations:

    • Variable Jump Height:

      Allow the player to control jump height by holding the jump button for a longer duration, applying a sustained upward force or adjusting the initial jump impulse.

    • Coyote Time:

      Provide a small window after leaving a platform where the player can still initiate a jump, improving the feel of the controls.

    • Wall Jumping:

      Implement logic to allow jumping off walls, often involving checking for horizontal collisions and applying an impulse in the opposite direction.

    • Jump-through Platforms:

      Allow the player to jump through platforms from below but land on them when falling from above. This often involves more complex collision filtering.



  • Webcam with OpenCV18:20

    How to use OpenCV and SDL3.

  • SDL3 Singleton14:16
    1. Singleton Design Pattern: This pattern ensures that a class has only one instance throughout the program's execution and provides a global point of access to that instance. This is useful for managing shared resources like a game engine core, a texture manager, or a renderer, where having multiple instances would be inefficient or problematic.

    2. Benefits in SDL3: Using the Singleton pattern for elements like the SDL_Renderer can centralize access to rendering functionalities and prevent issues that might arise from having multiple rendering contexts or conflicting rendering operations.

    3. Implementation Example (C++): A common C++ implementation for a singleton involves:

      • A private static member variable to store the single instance of the class.

      • A private constructor to prevent direct instantiation of the class.

      • A public static method (often named instance() or getInstance()) that returns the single instance, creating it if it doesn't already exist (lazy initialization).

  • SDL3 State Machine5:26

    A state machine, or finite state machine (FSM), breaks down a system's behavior into a set of distinct states and defines transitions between these states based on specific events.

  • State Machine14:25

    An example of a state machine using SDL3.

  • Spawn Instancing25:19

    In this section we look at some possible coding implementations using SDL3.

  • Scrolling Text21:51

    In this section we look at some possible coding implementations using SDL3.

  • Rotate Image8:51

    In this section we look at some possible coding implementations using SDL3.

  • Rescaling Images5:03

    In this section we look at some possible coding implementations using SDL3.

  • Render Tilemap12:15

    In this section we look at some possible coding implementations using SDL3.

  • SDL3 HUD Elements7:10

    The Heads Up Display can show all kinds of real-time data lets look at what SDL3 can help with.

  • Render Image16:25

    In this section we look at some possible coding implementations using SDL3.

  • Render Background Image6:35

    In this section we look at some possible coding implementations using SDL3.

  • Primitives8:47

    In this section we look at some possible coding implementations using SDL3.

  • Player Jump Gravity14:23

    In this section we look at some possible coding implementations using SDL3.

  • Play Music9:17

    In this section we look at some possible coding implementations using SDL3.

  • Object Moves to Player16:37

    In this section we look at some possible coding implementations using SDL3.

  • Move Image Mouse Click9:00

    In this section we look at some possible coding implementations using SDL3.

  • Move Image with Keyboard Press8:56

    In this section we look at some possible coding implementations using SDL3.

  • Level Collision Detection13:17

    In this section we look at some possible coding implementations using SDL3.

  • HUD Elements18:47

    In this section we look at some possible coding implementations using SDL3.

  • Fire Projectiles13:50

    In this section we look at some possible coding implementations using SDL3.

  • Pendulum Lab39:27

    Pendulum Simulations in C++:

    This is the most common interpretation. C++ is frequently used to create simulations of physical systems like pendulums, including simple pendulums, double pendulums, or even more complex systems like inverted pendulums or elastic pendulums. These simulations often involve:

    • Mathematical Modeling: Implementing the equations of motion (e.g., Lagrangian mechanics, Newton's laws) that describe the pendulum's behavior.

    • Numerical Integration: Using methods like Runge-Kutta to solve the differential equations and update the pendulum's state over time.

    • Graphical Visualization: Employing libraries like SFML, SDL, or even older graphics libraries like graphics.h to render the pendulum's movement on screen.

    • Interactive Elements: Allowing user interaction, such as adjusting parameters or applying forces.

  • Isometric Tilemap Locate the Tile Position7:50

    1. Get mouse coordinates

    Use SDL3's event system to capture mouse motion or button click events. The SDL_Event structure will contain the mouse's x and y coordinates within the window.


    #include <SDL3/SDL.h>


    // Inside your main game loop, within the event handling

    SDL_Event event;

    while (SDL_PollEvent(&event)) {

        if (event.type == SDL_EVENT_MOUSE_MOTION) {

            float mouseX = event.motion.x;

            float mouseY = event.motion.y;

            // Use mouseX and mouseY for further calculations

        }

    }


    2. Account for camera/scroll offset

    If your game has a moving camera or scrolling, you need to adjust the mouse coordinates to reflect their position relative to the world's origin (0,0) in isometric space.


    // Assuming camX and camY are the camera's X and Y offsets

    float adjustedMouseX = mouseX + camX - (SCREEN_WIDTH / 2); //SCREEN_WIDTH and SCREEN_HEIGHT are your window's dimensions

    float adjustedMouseY = mouseY + camY - (SCREEN_HEIGHT / 2);


    3. Convert screen coordinates to isometric tile coordinates

    This is the core of the calculation, and it depends on your specific isometric projection method and tile dimensions. Here's a common formula assuming a diamond-shaped isometric projection with the tile's origin at its top point:


    // Define your tile dimensions

    const int TILE_WIDTH_HALF = TILE_WIDTH / 2;

    const int TILE_HEIGHT_HALF = TILE_HEIGHT / 2;


    // Convert adjusted mouse coordinates to tile coordinates

    int tileX = (adjustedMouseX / TILE_WIDTH_HALF + adjustedMouseY / TILE_HEIGHT_HALF) / 2;

    int tileY = (adjustedMouseY / TILE_HEIGHT_HALF - adjustedMouseX / TILE_WIDTH_HALF) / 2;


    • TILE_WIDTH_HALF: Half the width of your isometric tile.

    • TILE_HEIGHT_HALF: Half the height of your isometric tile.


    4. Consider tile shape and offset

    • Diamond Shape: If your tiles are diamond-shaped, the formula above usually works well for flat surfaces.

    • Staggered/ZigZag: If your tiles are arranged in a staggered or zigzag pattern, you might need a slightly different formula or approach.

    • Offset for depth: If your tiles are sprites with different heights, consider accounting for these heights when calculating the tile Y position to ensure correct tile selection.


    5. Account for camera offset when drawing

    Remember that when drawing your tiles, you'll need to apply the camera offset to their isometric coordinates to position them correctly on the screen.

    Additional tips

    • Test and debug: Thoroughly test your coordinate conversion at various mouse positions, particularly at tile boundaries and corners, to ensure accurate tile selection.

    • Reference resources: Consult tutorials and articles on isometric math for deeper understanding and alternative projection methods that might suit your specific needs better.

    • Consider other selection methods: For complex tile shapes or multi-layered maps, exploring methods like collision detection with tile masks or using a separate rendering pass with unique colors for each tile can be beneficial.

  • SDL3 RTS15:45

    Developing a Real-Time Strategy (RTS) game with SDL3 can be efficiently structured using a component-based architecture. This approach enhances code organization, reusability, and scalability.

    Here's how you might approach the design of components and classes for an RTS game using SDL3:

    Core components and classes

    • SDL Core Components: SDL3 provides fundamental features like window management, event handling, and rendering, according to the SDL Wiki. These are the building blocks you'll utilize for the visual and interactive aspects of your game.

    • Component-Based Entity System: Instead of a deep inheritance hierarchy, which can become unwieldy, adopt a component-based system where game objects (entities) are composed of various components that define their behavior and data.

      • Component Class: A base Component class provides a common interface for all components, handling events, updates, and rendering.

      • Entity Class: An Entity acts as a container for various components. It manages the lifecycle of its components, including creation and destruction.


    Specialized RTS components

    • Units: The primary interactive elements in an RTS are units, such as soldiers, tanks, or gatherers.

      • Movement Component: Handles unit movement, potentially leveraging techniques like Flow Field Pathfinding for efficient movement of large groups.

      • Attack Component: Manages unit attacks, including target selection, damage calculations, and attack animations.

      • Resource Gathering Component: For units like villagers, this component handles resource collection and delivery.

    • Buildings: Buildings serve various purposes, from resource generation to unit training and defense.

      • Production Component: Enables buildings to train units or research technologies, often utilizing a queue and timers.

      • Defense Component: For defensive structures like towers, this component handles attacks against enemy units.

    • Resource Management: Crucial to RTS gameplay, resources like wood, stone, and gold need to be tracked and managed.

      • ResourceManager Class: Manages the game's resources, including tracking quantities, costs, and possibly implementing resource generation logic.

    • User Interface (UI): RTS games require a robust UI for unit selection, command issuance, and displaying game information.

      • Selection Component: Handles unit and building selection, potentially using physics queries for area selection.

      • Command Component: Processes player commands, translating them into actions for selected units or buildings. The Command Pattern can be beneficial here.

    • Game State Management: Manages different game states, such as menu, gameplay, and pause.


    Leveraging SDL3 features

    SDL3 provides powerful features that can be integrated into your RTS architecture:

    • Rendering: SDL3 allows for efficient rendering of textures, sprites, and animations for units and buildings.

    • Event Handling: Handle player input, including mouse clicks, keyboard presses, and potentially touch events for mobile RTS games.

    • Audio: Implement sound effects for unit actions, combat, and background music using SDL3's audio capabilities.

    • Camera API: Access webcams for features like in-game photo taking or video streaming, according to the SDL Wiki.


    Best practices

    • Component Composition: Focus on composing entities with different components rather than deep inheritance trees.

    • Data-Oriented Design (DOD): Consider leveraging DOD principles, especially for managing large numbers of units, to optimize performance.

    • Design Patterns: Familiarize yourself with relevant design patterns like the Singleton, Factory Method, and Observer patterns, which can be useful in various aspects of your game architecture.



  • 3D Modeling Software Overview43:28

    Other Modeler applications.

  • SDL3 Skeleton Program14:16

    Explore the SDL3 skeleton program and abi-driven workflow to initialize the library and manage input. Handle events, drive the app loop with app iterate, render, and clean up resources.

  • Class Inheritance2:35

    While C++ doesn't have a specific keyword for "interface" like some other languages, the concept is implemented using abstract classes and pure virtual functions.

    1. Abstract classes

    • An abstract class is a class with at least one pure virtual function.

    • It cannot be instantiated directly, but you can create pointers and references to it.

    • Abstract classes serve as blueprints for other classes, defining a common interface or contract that derived classes must follow.


    2. Pure virtual functions

    • A pure virtual function is declared in the base class using the virtual keyword followed by = 0.

    • It has no implementation in the base class, requiring derived classes to provide their own.

    • Pure virtual functions enable polymorphism and enforce that derived classes provide specific functionality.


    3. Implementing interfaces in C++

    • A common approach is to use pure abstract classes, which consist solely of pure virtual functions.

    • Alternatively, you can use abstract base classes that include both pure virtual functions and concrete functions with default implementations.

    • C++'s multiple inheritance feature allows classes to inherit from and implement multiple interfaces simultaneously.


    cpp

    // Example: Interface using a pure abstract class

    class Interface {

    public:

        virtual void method1() = 0;

        virtual int method2(int param) = 0;

        virtual ~Interface() = default; // It's recommended to have a virtual destructor in interfaces

    };


    class ConcreteClass : public Interface {

    public:

        void method1() override {

            // Implementation for Interface's method1

            // ...

        }


        int method2(int param) override {

            // Implementation for Interface's method2

            return param * 2;

        }

    };


    int main() {

        Interface* obj = new ConcreteClass(); // Using a base pointer to access the derived object

        obj->method1();

        obj->method2(5);

        delete obj;

        return 0;

    }


    Use code with caution.

    4. Key takeaways

    • Interfaces in C++ are implemented using abstract classes with pure virtual functions.

    • They enforce a contract for derived classes to adhere to, promoting code modularity, reusability, and polymorphism.

    • While abstract classes can have both pure virtual and concrete functions, interfaces typically consist only of pure virtual functions.

    • Multiple inheritance allows classes to implement multiple interfaces simultaneously in C++.

  • SDL3 Top Down Shooter22:33
  • SDL3 Pathfinding Image with Mouse Click9:32

    How to use SDL3 in an application using your mouse.

  • SDL3 Class Organization18:27

    Small talk about loading in external files in C++ and the difference between structs and classes in C++.

  • RPG Player Skills19:46

    In role-playing games (RPGs), player skills encompass a range of abilities and proficiencies that characters possess, impacting their actions and interactions within the game world. These skills are often categorized into physical, mental, social, and combat-related abilities, with some games featuring more specialized or esoteric skills as well.

  • SDL3 Pathfinding with Image12:58

    If you're looking for information on using pathfinding concepts in the context of SDL3 (Simple DirectMedia Layer 3) in a class setting, here's a breakdown of the key information gathered from the search results:

    Pathfinding Concepts for SDL3

    • Understanding Pathfinding: Pathfinding involves finding an optimal or near-optimal path between two points in a given space, considering various factors like obstacles, terrain costs, and movement capabilities.

    • Common Algorithms: Several algorithms exist for pathfinding, with the A* (A-Star) algorithm being a popular choice for games due to its efficiency in finding the shortest path on a weighted graph, according to Yellowbrick. Other algorithms include Dijkstra's algorithm, Breadth-First Search (BFS), and Depth-First Search (DFS), each with its own strengths and applications.

    • Implementing Pathfinding with SDL3: SDL3 itself doesn't provide a built-in pathfinding solution. Instead, you would implement the chosen pathfinding algorithm (e.g., A*) and then use SDL3's drawing and rendering functions to visualize the path and manage the movement of your game objects along that path.

    • Steps for Implementation:

      1. Define your game environment: This involves representing your game world (e.g., as a grid, graph, or navmesh) where pathfinding will occur.

      2. Implement the chosen algorithm: Write the C++ (or other language) code to implement the pathfinding algorithm, including data structures for nodes, obstacles, and path segments.

      3. Integrate with SDL3: Use SDL3 functions for:

        • Rendering: Draw the path, obstacles, and moving objects on the screen.

        • Input and Event Handling: Allow the player to interact with the game, such as selecting a destination for pathfinding.

        • Timer and Game Loop: Manage game time and update the position of objects based on the calculated path, as shown in this YouTube tutorial.


    Resources for Learning and Practice

    • SDL3 Tutorials:

      • The SDL Wiki offers tutorials and examples for SDL3 functionalities, though not specifically focused on pathfinding.

      • Mike Shah's SDL3 course provides a free course based on his YouTube videos on SDL3, according to Mike Shah's website.

    • Pathfinding Algorithm Resources:

      • Online resources and textbooks on algorithms and artificial intelligence in games often provide explanations and implementations of pathfinding algorithms.

      • Game development forums and communities like Reddit's r/gamedev can also be good sources for information and discussion on pathfinding in games.

    • Open-Source Projects: Explore open-source game projects or AI pathfinding implementations on platforms like GitHub for examples of how others have approached pathfinding using SDL or similar frameworks. For instance, one GitHub repository demonstrates C++ SDL AI pathfinding using various algorithms like BFS, Dijkstra, and A*.


    Important Note: SDL3 is a relatively new library, and while it builds upon SDL2, the learning resources specifically tailored for SDL3 are still evolving. If you encounter difficulty finding comprehensive SDL3 pathfinding tutorials, considering learning pathfinding with SDL2 first could be helpful, as the core concepts and many functionalities remain similar.

  • SDL3 Mouse Click Events3:01

    Detecting mouse click events in SDL3

    To detect mouse click events in SDL3, you'll need to use the event subsystem and listen for specific event types.

    Here's a breakdown of how to achieve this:

    1. Poll for events: Your main application loop should continuously check for new events using SDL_PollEvent(&e).

    2. Identify mouse button events: Within the event loop, examine the e.type field to determine the event type. For mouse clicks, you're looking for:

      • SDL_EVENT_MOUSE_BUTTON_DOWN: Indicates a mouse button has been pressed.

      • SDL_EVENT_MOUSE_BUTTON_UP: Indicates a mouse button has been released.

    3. Access mouse button event data: If the event type is either SDL_EVENT_MOUSE_BUTTON_DOWN or SDL_EVENT_MOUSE_BUTTON_UP, the event data will be stored in an SDL_MouseButtonEvent structure, accessible via the e.button member of the SDL_Event union.

    4. Extract information: The SDL_MouseButtonEvent structure provides several useful fields:

      • button: Indicates which mouse button was pressed (e.g., SDL_BUTTON_LEFT, SDL_BUTTON_RIGHT, SDL_BUTTON_MIDDLE, etc.).

      • x, y: Provide the mouse cursor's coordinates (relative to the window) at the time of the event.

      • clicks: Indicates the number of clicks (e.g., 1 for single-click, 2 for double-click).

      • down: A boolean value, true if the button is pressed, false if released.


    #include "SDL.h"


    // In your event loop:

    SDL_Event e;

    while (SDL_PollEvent(&e)) {

        switch (e.type) {

            case SDL_QUIT:

                // Handle quit event

                break;

            case SDL_EVENT_MOUSE_BUTTON_DOWN:

                // Mouse button pressed

                if (e.button.button == SDL_BUTTON_LEFT) {

                    // Handle left-click down

                    SDL_Log("Left mouse button down at (%f, %f)", e.button.x, e.button.y);

                }

                break;

            case SDL_EVENT_MOUSE_BUTTON_UP:

                // Mouse button released

                if (e.button.button == SDL_BUTTON_RIGHT) {

                    // Handle right-click up

                    SDL_Log("Right mouse button up at (%f, %f)", e.button.x, e.button.y);

                }

                break;

            default:

                // Handle other event types

                break;

        }

    }


  • SDL3 Tiled Map8:32

    SDL3 provides a framework for creating and displaying tilemaps, which are commonly used in 2D games and applications to represent game worlds or environments.

    Here's how to display a tilemap using SDL3, often in conjunction with a tilemap editor like Tiled:

    1. Load the tileset

    • A tileset is an image containing all the individual tiles used in the map.

    • You'll need to load the tileset image into an SDL_Surface or SDL_Texture.

    • You'll also need to parse the tileset data (e.g., from a JSON file generated by a tilemap editor like Tiled) to extract information about the individual tiles, such as their IDs, dimensions, and image coordinates.


    2. Load the tilemap data

    • The tilemap data defines the layout of the tiles, specifying which tile appears at each position in the map.

    • This data can also be loaded from a file (e.g., JSON or XML) generated by a tilemap editor.


    3. Create an SDL3 renderer

    • An SDL3 renderer is required to draw the tiles to the screen.

    • You can create a renderer using SDL_CreateRenderer, specifying the window you want to render to and the desired rendering flags.


    4. Iterate through the tilemap and render each tile

    • Loop through the rows and columns of your tilemap data.

    • For each tile, retrieve its corresponding image data from the tileset.

    • Use SDL_RenderCopy to copy the tile's image from the tileset texture to the appropriate position on the screen, applying any necessary transformations or offsets.

    • Consider using techniques like view frustum culling to avoid rendering tiles outside the visible area, improving performance.


    5. Handle user input and game logic

    • Use SDL_PollEvent to handle keyboard and mouse input for scrolling the map, interacting with objects, etc.

    • Update game logic (e.g., player movement, enemy AI) and adjust the tilemap's position or the camera view accordingly.


    6. Optimize rendering (for large tilemaps)

    • Consider rendering the entire tilemap or large chunks of it to a separate texture once, and then rendering that texture to the screen in subsequent frames, especially for static background tiles.

    • This can significantly reduce the number of SDL_RenderCopy calls and improve performance.

    • If your tilemap includes animated tiles, you'll need to update them as individual entities or use more advanced rendering techniques.

  • SDL3 Procedural Generation17:55

    SDL3, while not a procedural generation engine itself, provides the tools and infrastructure to implement various procedural generation techniques within your applications, particularly for games and simulations.

    Here's how SDL3 supports procedural generation:

    • Rendering capabilities: SDL3's rendering API allows you to draw generated content, whether it's terrain, textures, or shapes. The SDL3 GPU API offers more advanced control over the rendering pipeline, including access to compute shaders which can be used for procedural generation on the GPU.

    • Texture creation: You can create textures dynamically in SDL3 to store and display procedurally generated patterns or data.

    • Event handling: SDL3 handles various events, such as user input, which can be used to influence the parameters or algorithms of your procedural generation, allowing for dynamic and interactive content creation.

    • Audio generation: SDL3 also includes features for procedural audio generation, allowing you to create sound effects and music algorithmically.


    Examples of procedural generation using SDL3

    • Procedural Terrain Generation: Tutorials exist demonstrating how to generate terrains using algorithms like Perlin Noise and render them as textures in SDL3.

    • Procedural Map Generation: Examples show how to generate maps with different biomes and features using techniques like random point selection within quadrants and cellular automata.

    • Procedural Texture Generation: You can generate textures with various patterns and details, like noise-based textures for natural-looking surfaces.

    • Procedural Audio Generation: Generating audio waveforms, like sine waves, is possible in SDL3 for creating sound effects or music.


    Key principles

    • Algorithms and rules: Procedural generation relies on algorithms and predefined rules to create content. Examples include Perlin Noise for terrain generation, Wave Function Collapse for map structures, and cellular automata for various patterns.

    • Randomness and control: Procedural generation often involves randomness, but it's important to differentiate it from purely random generation. Procedural generation employs controlled variability, ensuring a degree of structure and predictability while allowing for diversity.

    • Iterations and layering: Complex procedural generation often involves layering multiple techniques and processing them iteratively, for instance, using noise functions for terrain height, then adding details with other methods.


    In essence, SDL3 provides the fundamental building blocks (rendering, textures, events) for you to implement and display the results of your procedural generation algorithms. You can craft the logic for generating content using various techniques and then use SDL3 to bring that content to life visually and audibly within your applications.

  • SDL3 Delete Object2:49

    In SDL3 (Simple DirectMedia Layer 3), deleting an object, such as a surface or texture, involves freeing the associated memory to prevent memory leaks. This is typically done by calling specific SDL functions designed for object destruction. For example, SDL_DestroyTexture() is used for textures and SDL_FreeSurface() for surfaces.

    Here's a breakdown of how to delete different types of objects in SDL3:


    1. SDL_Texture:

    • To delete an SDL_Texture, use SDL_DestroyTexture(texture).

    • This function releases the memory associated with the texture.

    • Ensure you've released all resources associated with the texture before calling this function, such as renderers or other textures that might be using it as a source.


    2. SDL_Surface:

    • To delete an SDL_Surface, use SDL_FreeSurface(surface).


    • This function frees the memory allocated for the surface.

    • If the surface was created from a loaded image file, ensure you've also freed the image data (e.g., using SDL_RWclose() if you loaded it from a custom read/write object).


    3. SDL_Window:

    • To delete an SDL_Window, use SDL_DestroyWindow(window).

    • This function destroys the window and releases its resources.

    • It's important to destroy the window before the application exits, as it might prevent issues with other SDL operations.


    4. SDL_Renderer:

    • To delete an SDL_Renderer, use SDL_DestroyRenderer(renderer).

    • This function destroys the renderer and releases its resources.

    • Make sure to destroy all textures associated with the renderer before destroying the renderer itself.


    5. SDL_GLContext:

    • To delete an SDL_GLContext, use SDL_GL_DestroyContext(context).

    • This function destroys the OpenGL context.

    • It should only be called on the main thread.


    General Guidelines:

    • Always free resources when they are no longer needed to avoid memory leaks.

    • Destroy objects in the reverse order of their creation. For example, destroy textures before destroying the renderer that created them.

    • Use SDL_GetError() to check for errors after calling SDL functions. This can help diagnose issues during object destruction.


    • Consider using smart pointers (like std::unique_ptr or std::shared_ptr) in C++ to automatically manage object lifetimes and prevent memory leaks, according to GameDev.net.

  • SDL3 Pathfinding12:53

    When implementing A* pathfinding in C++ for an SDL3 project, you'll generally want to structure your code into distinct classes to maintain organization and reusability. Here's a breakdown of common classes and their roles:

    1. Node class

    • Purpose: Represents a single point or cell in your grid or graph used for pathfinding.

    • Attributes:

      • Coordinates (e.g., int x, int y).

      • gCost: Cost from the start node to the current node.

      • hCost: Heuristic cost (estimated cost from current node to end node).

      • fCost: Total cost (gCost + hCost).

      • parent: A pointer or reference to the previous node in the path (important for reconstructing the path once found).

      • isWalkable: A boolean indicating whether the node can be traversed.

      • terrainCost: (Optional) Additional cost associated with traversing this node due to terrain type, etc.

    • Methods:

      • Constructors for initializing node data.

      • Methods to calculate and update gCost, hCost, and fCost values.

      • Overloaded operators (e.g., <) to allow nodes to be stored in std::set or std::priority_queue.


    2. Grid or Map class

    • Purpose: Manages the overall grid structure and provides access to individual nodes.

    • Attributes:

      • 2D array or std::vector of Node objects representing the grid.

    • Methods:

      • Constructor to initialize the grid (e.g., setting dimensions, marking obstacles).

      • Method to get a node at specific coordinates.

      • Method to determine if a given coordinate is within the grid boundaries.

      • Method to check if a node is walkable or blocked.


    3. AStarPathfinder class

    • Purpose: Encapsulates the A* pathfinding algorithm logic.

    • Attributes:

      • Reference to the Grid or Map object.

      • openList: A std::priority_queue to store nodes to be evaluated (ordered by fCost).

      • closedList: A std::set or std::vector to store nodes already evaluated.

    • Methods:

      • Constructor to take the Grid object.

      • findPath(Node startNode, Node endNode): The core A* algorithm method:

        • Initializes openList and closedList.

        • Iteratively selects the lowest fCost node from openList.

        • Evaluates neighbors, updates gCost, hCost, fCost values, and adds/updates nodes in openList and closedList.

        • Reconstructs and returns the path (e.g., as a std::vector of nodes or SDL_Point objects) according to GitHub.

      • Helper methods:

        • calculateHCost(Node a, Node b): Calculates the heuristic cost between two nodes (e.g., using Manhattan or Euclidean distance).

        • getNeighbors(Node node): Returns a list of valid, traversable neighbors for a given node.


    4. Game class (or GameEngine)

    • Purpose: Integrate the A* pathfinding into your game logic.

    • Attributes:

      • Instances of Grid and AStarPathfinder classes.

    • Methods:

      • Calls the findPath method from the AStarPathfinder class when pathfinding is needed (e.g., when an enemy needs to move to the player's position).

      • Processes the returned path and updates object positions accordingly.

      • Renders the game, including the pathfinding visualization (optional, for debugging).


    Example class relationships

    mermaid

    classDiagram

        class Node {

            +int x

            +int y

            +int gCost

            +int hCost

            +int fCost

            +Node* parent

            +bool isWalkable

            +int terrainCost

        }

        class Grid {

            +std::vector<std::vector<Node>> nodes

            +getNode(int x, int y): Node&

            +isWithinBounds(int x, int y): bool

            +isWalkable(int x, int y): bool

        }

        class AStarPathfinder {

            -Grid& grid

            -std::priority_queue<Node> openList

            -std::set<Node> closedList

            +findPath(Node start, Node end): std::vector<Node>

            -calculateHCost(Node a, Node b): int

            -getNeighbors(Node node): std::vector<Node>

        }

        class Game {

            -Grid gameGrid

            -AStarPathfinder pathfinder

            +update()

            +render()

        }

        Grid --o Node: contains

        AStarPathfinder --o Grid: uses

        Game --o Grid: uses

        Game --o AStarPathfinder: uses


  • Menu in SDL333:38
    • Create your own menu class structure:

      This involves defining classes or structures to represent menu items, buttons, or other interactive elements.

    • Handle rendering:

      Use SDL3's rendering functions (e.g., SDL_RenderCopy, SDL_RenderGeometry) to draw the visual representation of your menu elements (shapes, textures, text using an add-on library like SDL_ttf).

    • Manage input events:

      Process user input (mouse clicks, keyboard presses) using SDL3's event handling system (SDL_PollEvent, SDL_Event) to determine interactions with your menu elements and trigger appropriate actions.

    • Implement menu logic:

      Design the flow of your menu, including navigating between sub-menus, handling selections, and transitioning to other game states or actions.

    Alternative Approaches:

    • Third-party GUI libraries:

      Consider using a separate GUI library designed to work with SDL, such as Dear ImGui or Nuklear, if you need more complex UI elements or a faster development process for your menu system.

  • Gold PickUp Radius4:10

    A pickup radius for gold in a game developed with SDL3 in C++ typically involves checking the distance between the player and any nearby gold items.

    Here's a breakdown of how you might implement this:

    1. Representing Player and Gold:

      • Define classes or structs for your Player and Gold objects. These should contain at least their x and y coordinates (or perhaps SDL_Rect for rendering and collision).

    2. Calculating Distance:

      • To determine if a gold item is within the player's pickup radius, you'll need to calculate the distance between their centers.

      • The Euclidean distance formula is generally appropriate:
        distance = sqrt( (player.x - gold.x)^2 + (player.y - gold.y)^2 )

      • For performance, you might compare squared distances to avoid sqrt if you only need to check if the distance is less than or equal to the radius.

    3. Defining the Pickup Radius:

      • The pickup radius is a numerical value (e.g., in pixels or game units) that defines the area around the player within which gold can be picked up.

      • You could store this as a member variable of the Player class or as a global constant.

    4. Checking for Pickup:

      • In your game loop, iterate through all available gold items.

      • For each gold item, calculate the distance to the player.

      • If the distance is less than or equal to the pickup radius, consider the gold picked up and remove it from the game.


    Example (simplified pseudocode):

    cpp

    // Player class (with position and pickup radius)

    class Player {

    public:

        float x, y;

        float pickupRadius;

        // ...

    };


    // Gold class (with position)

    class Gold {

    public:

        float x, y;

        // ...

    };


    // ... inside your game loop ...

    for (auto& gold : allGoldItems) {

        float distance = calculateDistance(player.x, player.y, gold.x, gold.y);


        if (distance <= player.pickupRadius) {

            // Gold picked up!

            player.addGold(gold.value);

            gold.remove(); // Mark for removal

        }

    }


    // Remove collected gold items from the game world.


    Additional Considerations:

    • SDL Structures: Use SDL_FPoint for floating-point coordinates or SDL_Point for integer coordinates to represent positions.

    • Collision Detection: While direct distance calculation works, more complex collision detection (like circle-to-circle collision if you have circular boundaries around player and gold) could be used. According to Reddit collisions between circles can be determined if the center position of circle A is less than 1 radius length away from circle B's center.

    • Performance: For a large number of gold items, consider using spatial partitioning techniques like a quadtree to optimize collision checks, especially if you have many objects in your game world.

  • Fighting Game Class SDL311:42

    Building a fighting game with SDL3 and C++ involves structuring your code effectively using classes. Here's a breakdown of key classes you might consider and best practices:

    Core game classes

    • Game class: This would be your central class, managing the main game loop, handling events, updating game states, and rendering all game elements.

    • Fighter (or Character) class: This would represent the individual fighters. It could hold data like:

      • Position and movement (using SDL_Rect, for instance).

      • Health and other stats.

      • Current animation frame and state.

      • Input handling logic specific to that character.

      • Methods for updating its state (e.g., updatePosition(), handleInput()) and rendering itself (render()).

    • Animation class: A class or component to manage animations for characters and other entities, including:

      • Loading and managing sprite sheets or individual frames.

      • Updating animation frames based on character state or actions.

      • Possibly using techniques like atlasing for optimized rendering, where a single mega-texture holds all animation frames, according to gamedev.stackexchange.com.

    • InputHandler class: Separating input management from the game and character logic can be beneficial. This class could:

      • Gather input from keyboard, mouse, and game controllers.

      • Translate raw input into game actions (e.g., "move left," "attack").

      • Make this input available to other parts of your game, like the Fighter class.

    • PhysicsComponent or CollisionManager: Fighting games require precise collision detection and physics for character interaction and hitboxes. These classes could handle:

      • Collision detection between characters and other game elements.

      • Applying physics-based movement and reactions (e.g., knockback, jumps).

    • SoundManager and TextureManager (or AssetManager): These classes would manage the loading, unloading, and access to game assets like sounds, music, and textures. This helps centralize resource management and avoids redundant loading.


    Best practices and tips

    • Prioritize clarity and modularity: Break down your game into smaller, manageable classes, each responsible for a specific aspect. This makes your code easier to understand, maintain, and debug.

    • Avoid excessive inheritance: While useful, overusing inheritance can lead to complex class hierarchies. Consider using composition (combining smaller objects to build larger ones) for greater flexibility.

    • Focus on data locality: When possible, keep data that is used together close in memory. This can improve performance by reducing cache misses.

    • Think about game state management: How will you transition between different game states (main menu, character selection, fighting, game over)? A state machine pattern can be helpful here.

    • Start simple: Don't try to build the next AAA fighting game from scratch immediately. Start with a basic movement system and collision detection, and incrementally add features like animations, special moves, and sound.

    • Consult tutorials and examples: The SDL Wiki provides examples, and many online tutorials demonstrate how to use SDL3 and C++ for game development, including specific examples related to fighting games, according to the SDL Wiki.


    Remember that the exact class structure will depend on the specific features and complexity of your fighting game. As you develop, you might refine or add to this list of classes based on your needs.

  • SDL3 Texture Manager3:32
  • Custom Game User Interface with SDL326:46

    Building a Custom UI Class with SDL3 and C++

    SDL3 itself doesn't directly offer UI widgets like buttons or text fields. Instead, it provides the fundamental building blocks (like rendering and event handling) that allow you to construct your own custom UI elements and frameworks.

    1. The foundation: UI class

    • You can create a base UI class to manage your custom UI components.

    • This class would likely hold a collection (e.g., std::vector) of your individual UI elements.


    2. UI element base class

    • Inheritance: Create a base class for your UI elements (e.g., UIComponent), from which specific elements like buttons, sliders, etc., can inherit.

    • Rendering: Each component will need a Render() function (perhaps a virtual function to allow specialized rendering for each component type) to draw itself on the screen using SDL's rendering functions.

    • Event Handling: Implement a HandleEvent() function (again, possibly virtual) to process SDL events relevant to the component, such as mouse clicks, keyboard input, etc.


    3. Example: A simple button class

    • Inheritance: Your Button class could inherit from UIComponent (or even directly from a basic shape like Rectangle).

    • Properties: It would likely have properties like position, size, text, and color.

    • Event Handling: In the HandleEvent() method, it would check for mouse clicks or hover events within its bounds.

    • Callbacks/Observers: You can implement callback mechanisms to trigger specific actions when the button is clicked, either through function pointers or by using the observer pattern.


    4. UI hierarchy and management

    • Manager Classes: For complex interfaces, you can create manager classes to group and manage sections of the UI (e.g., a menu manager).

    • Delegation: These managers can then delegate event handling and rendering to their child components.


    5. Integrating with the SDL event loop

    • Main Loop: Your application's main loop will continuously poll SDL events.

    • Dispatching Events: In the event loop, you would dispatch events to your top-level UI manager or individual components as needed.

    • Rendering: After processing events, the main loop would call the Render() methods of your UI elements or manager to draw them on the screen.


    6. Additional considerations

    • Layout and Positioning: Implement a system for arranging UI elements (e.g., anchoring, scaling, and automatic layout).

    • Theming: Create a theming system to customize the appearance of your UI elements.

    • Text Rendering: Utilize SDL_ttf or other libraries for rendering text on your buttons and other UI elements.


    Note

    • You can also explore existing SDL2 GUI toolkits or libraries like Guisan. You might need to adapt them to work with SDL3 or consider integrating other C++ UI libraries that are compatible with SDL3, such as RmlUI.

  • SDL3 Space Shooter Class17:52

    Build a SDL3 space shooter class with a game loop, input handling, and rendering. Implement the player, enemies, and projectiles, load textures, and parallax scrolling.

  • SDL3 Inventory LookUp System3:22
  • SDL3 Event Button3:31

    In SDL3, mouse button events are handled through the SDL_Event union and specifically the SDL_MouseButtonEvent structure. There isn't a dedicated "button class" in SDL3 itself for handling GUI buttons; rather, you detect mouse button presses and releases, and then typically implement your own logic to determine if a "button" area on the screen was clicked.

    Here's how you work with SDL3 mouse button events in C++:

    • Poll for Events: Use SDL_PollEvent() within your main application loop to retrieve events from the event queue.

    C++

        SDL_Event event;    while (SDL_PollEvent(&event)) {        // Process events here    }

    • Check Event Type: Inside the event loop, check if the event.type is SDL_EVENT_MOUSE_BUTTON_DOWN or SDL_EVENT_MOUSE_BUTTON_UP to detect button presses or releases, respectively.


    C++

        switch (event.type) {        case SDL_EVENT_MOUSE_BUTTON_DOWN: {            // Handle mouse button down event            break;        }        case SDL_EVENT_MOUSE_BUTTON_UP: {            // Handle mouse button up event            break;        }        // ... other event types    }

    • Access Button Event Data: When a mouse button event occurs, the relevant data is stored in the event.button member of the SDL_Event union, which is an SDL_MouseButtonEvent structure.


    C++

        const SDL_MouseButtonEvent& mouse_event = event.button;

    • Extract Button Information: The SDL_MouseButtonEvent structure provides details about the button event:

    • mouse_event.button: The specific mouse button that was pressed or released (e.g., SDL_BUTTON_LEFT, SDL_BUTTON_RIGHT, SDL_BUTTON_MIDDLE).


    • mouse_event.x, mouse_event.y: The X and Y coordinates of the mouse cursor at the time of the event.


    • mouse_event.down: A boolean indicating whether the button is currently pressed (true) or released (false).


    • mouse_event.clicks: Indicates if it's a single-click (1), double-click (2), etc.


    C++

        if (mouse_event.button == SDL_BUTTON_LEFT) {        // Left mouse button clicked        std::cout << "Left button clicked at: " << mouse_event.x << ", " << mouse_event.y << std::endl;    }

    Creating a C++ Button Class (User-Defined):

    To create interactive buttons in your SDL3 application, you would typically implement your own C++ class that:

    • Manages its position and size: Often using an SDL_Rect.

    • Draws itself: Using SDL rendering functions.

    • Handles mouse events: By checking if the mouse click coordinates fall within its bounding box and then performing an action (e.g., calling a callback function).

    C++

    // Example of a basic Button class structure (simplified)class Button {public:    Button(int x, int y, int w, int h) : m_rect({x, y, w, h}) {}    void handleEvent(const SDL_Event& event) {        if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {            const SDL_MouseButtonEvent& mouse_event = event.button;            if (mouse_event.button == SDL_BUTTON_LEFT &&                mouse_event.x >= m_rect.x && mouse_event.x < m_rect.x + m_rect.w &&                mouse_event.y >= m_rect.y && mouse_event.y < m_rect.y + m_rect.h) {                onClick(); // Call a virtual function or a callback            }        }    }    virtual void onClick() = 0; // Pure virtual function for custom button behavior    // ... other drawing and utility methodsprotected:    SDL_Rect m_rect;};

  • Character Sprite tutorial41:42

    Learn to create a custom playable character sprite using a free template.

  • SDL3 Spawn Instancing5:26
  • Adding Music and Sound Effects to our SDL3 Project9:54

    Playing music and sound effects in SDL3 using C++ typically involves the SDL_mixer library, which is an add-on to SDL designed specifically for audio playback.

    Here's a general approach to creating a C++ class for music and sound with SDL3:

    • Include Headers: Include necessary SDL and SDL_mixer headers.


        #include <SDL.h>    #include <SDL_mixer.h>    #include <string>

    • Initialize SDL_mixer: Call Mix_OpenAudio() to initialize the audio system and Mix_Init() with the desired audio formats.



        if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {        // Handle error    }    Mix_Init(MIX_INIT_MP3 | MIX_INIT_OGG); // Or other formats

    • Create a Music Class:

    • Data Member: Store Mix_Music* to hold the loaded music.


    • Constructor: Load music from a file using Mix_LoadMUS().


    • Destructor: Free the music with Mix_FreeMusic().


    • Play Method: Use Mix_PlayMusic() to play the music, specifying the number of loops.


    • Stop Method: Use Mix_HaltMusic() to stop the music.


    • Pause/Resume Methods: Use Mix_PauseMusic() and Mix_ResumeMusic().



        class MusicPlayer {    public:        MusicPlayer(const std::string& filePath) {            music = Mix_LoadMUS(filePath.c_str());            if (!music) {                // Handle error            }        }        ~MusicPlayer() {            if (music) {                Mix_FreeMusic(music);            }        }        void play(int loops = -1) { // -1 for infinite loops            if (music) {                Mix_PlayMusic(music, loops);            }        }        void stop() {            Mix_HaltMusic();        }        void pause() {            Mix_PauseMusic();        }        void resume() {            Mix_ResumeMusic();        }    private:        Mix_Music* music;    };

    • Create a Sound Effect Class:

    • Data Member: Store Mix_Chunk* to hold the loaded sound effect.


    • Constructor: Load sound from a file using Mix_LoadWAV().


    • Destructor: Free the sound with Mix_FreeChunk().

    • Play Method: Use Mix_PlayChannel() to play the sound on a specific channel, specifying the number of loops.



        class SoundEffect {   

    public:        SoundEffect(const std::string& filePath) {            chunk = Mix_LoadWAV(filePath.c_str());            if (!chunk) {                // Handle error            }        }        ~SoundEffect() {            if (chunk) {                Mix_FreeChunk(chunk);            }        }        void play(int loops = 0, int channel = -1) { // 0 for no loops, -1 for any available channel            if (chunk) {                Mix_PlayChannel(channel, chunk, loops);            }        }    private:        Mix_Chunk* chunk;    };

    • Clean Up: Call Mix_CloseAudio() and Mix_Quit() before quitting SDL.



        Mix_CloseAudio();    Mix_Quit();    SDL_Quit();

  • SDL3 Serialization6:15

    Sometimes you want to decode information sent over the network.

  • SDL3 Sound Clip Music Loop5:55

    Lets talk about the SDL3_Mixer system.

  • SDL3 Spawn Instancing6:58

    Making more than one object of the same type is useful in simulations.

  • SDL3 Multithreading12:46
  • SDL3 Depth First Search11:53

    One of many graph search Algorithms , DFS is a common well known technique.

  • Save Data to file5:31

    There are times when people want to pull in data or read information from an external source in other applications including video games.

  • SDL3 Breadth-First Search7:16

    One of many search techniques BFS is usually used in graph networks.

  • SDL3 Crop Image From Tilemap7:45

    Using parts of a tile sheet for a game map.

  • Pong game class sdl313:59
  • Breakout SDL3 Homwork2:11
  • SDL3 Mouse Image Button Press7:26

    A small talk about how event actions work for the mouse.

  • SDL3 Scrolling Text5:01

    Output information in a particular location using SDL3_ttf.

  • SDL3 Inventory2:11

    Storing data items in a collection using C++.

  • SDL3 Client Server Application8:15
  • SDL3 Rougelike46:56

    If you played games like Dwarf Fortress and Rouge you will want to learn these concepts.

  • SDL3 Pathfinding Image Mouse9:32

    Lets see if we can visualize our paths with  a mouse click.

  • SDL3 Network lobby7:07

    Clients in online games join a "Lobby " to wait for online connections to see if there are vacancies for online games.

  • Testing Our Finished Game Project13:07

    We have our 2D Game Engine sort of working now lets look over and review what we have learned using the Simple Directmedia Layer 3 and the C++ programming language.

Requirements

  • A person may be a bit familar with C++ programming and Object Oriented Programming before begining this course. There will be some work with using data structures and the C++ programming langage to create game obects.
  • Computer Graphics Course , Understanding of Linear Algebra

Description

Watch Cyber Monday SDL3  Action Adventure Role Playing Game in C++. I am sure you love to play video games why not learn to program them instead. The Simple Directmedia Layer 3 is hot and new and has transition from an API to an ABI to go along with some of the modern standards of programming. In this course we will use some Data Structures in order to optimize the game performance.  In this long course series learn how to create a 2D or 3D action adventure role playing game using  SDL3 to create something similar to your favorite PC game titles. If you ever wondered how to make in inventory system in  or make enemies follow the player in a map this video series is for you. The classes will be short and straight to the point with a presentation then some actual coding will take place and also talk about Object Oriented Programing for  Game Design. Also learn how to add sound, music and online network server play for your game title. If you are tired of playing Hero Siege or Diablo 2 then make your own. The best place to start learning is right here so Join today.

Who this course is for:

  • Mid-Level C++ Programmers.
  • Anyone wanting to make a fun game fast using C++.