Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Author Posts - Game Development

4 Articles
article-image-artificial-intelligence-in-game-development-understanding-behavior-trees
Marco Secchi
18 Nov 2024
10 min read
Save for later

Artificial Intelligence in Game Development: Understanding Behavior Trees

Marco Secchi
18 Nov 2024
10 min read
IntroductionIn the wild world of videogames, you'll inevitably encounter a foe that needs to be both engaging and captivating. This opponent isn't just a bunch of nice-to-see polygons and textures; it needs to be a challenge that'll keep your players hooked to the screen.Let's be honest, as a game developer, crafting a truly engaging opponent is often a challenge that rivals the one your players will face!In video games, we often use the term Artificial Intelligence (AI) to describe characters that are not controlled by the player, whether they are enemies or friendly entities. There are countless ways to develop compelling characters in video games. In this article, we'll explore one specific solution offered by Unreal Engine: behavior trees.NoteCitations come from my Artificial Intelligence in Unreal Engine 5 book.Using the Unreal Shooting Gym ProjectFor this article, I have created a dedicated project called Unreal Shooting Gym. You can freely download it from GitHub: https://github.com/marcosecchi/unreal-shooting-gym and open it up with Unreal Engine 5.4.Once opened, you should see a level showing a lab with a set of targets and a small robot armed with a gun (A.K.A. RoboGun), as shown in Figure 1: Figure 1. The project level.If you hit the Play button, you should notice the RoboGun rotating toward a target while shooting. Once the target has been hit, the RoboGun will start rotating towards another one. All this logic has been achieved through a behavior tree, so let’s see what it is all about.Behavior Trees“In the universe of game development, behavior trees are hierarchical structures that govern the decision-making processes of AI characters, determining their actions and reactions during gameplay.”Unreal Engine offers a solid framework for handling behavior trees based on two main elements: the blackboard and behavior tree assets.Blackboard Asset“In Unreal Engine, the Blackboard [...] acts as a memory space – some sort of brain – where AI agents can read and write data during their decision-making process.“By opening the AI project folder, you can double-click the BB_Robogun asset to open it. You will be presented with the blackboard that, as you can see from Figure 2, is quite simple to understand. Figure 2. The AI blackboardAs you can see there’s a couple of variables – called keys – that are used to store a reference to the actor owning the behavior tree – in this case, the RoboGun – and to the target object that will be used to rotate the RoboGun.Behavior Tree Asset“In Unreal Engine, behavior trees are assets that are edited in a similar way to Blueprints – that is, visually – by adding and linking a set of nodes with specific functionalities to form a behavior tree graph.”Now, double-click the BT_RoboGun asset located in the AI folder to open the behavior tree. You should see the tree structure depicted in Figure 3:Figure 3. The AI behavior treeAlthough this is a pretty simple behavior logic, there’s a lot of things involved here. First of all, you will notice that there is a Root node; this is where the behavior logic starts from.After that, you will see that there are three gray-colored nodes; these are defined composite nodes.“Composite nodes define the root of a branch and set the rules for its execution.”Each of them behaves differently, but it is sufficient to say that they control the subtree that will be executed; as an example, the Shoot Sequence node will execute all the subtrees one after the other.The purple-colored nodes are called tasks and they are basically the leaves of the tree, whose aim is to execute actions. Unreal Engine comes with some predefined tasks, but you will be able to create your own through Blueprints or C++.As an example, consider the Shoot task depicted in Figure 4: Figure 4. The Shoot task In this Blueprint, when the task is executed, it will call the Shoot method – by means of a ShootInterface – and then end the execution with success. For a slightly more complex task, please check the  BTTask_SeekTarget asset.Get back to the behavior tree, and you will notice that the Find Random Target node has a blue-colored section called Is Target Set? This is a decorator. “Decorators provide a way to add additional functionality or conditions to the execution of a portion of a behavior tree.”In our case, the decorator is checking if the TargetActor blackboard key is not set; the corresponding task will be executed only if that key is not set – that is, we have no viable target. If the target is set, this decorator will block task execution and the parent selector node – the Root Selector node – will execute the next subtree.Environment QueriesUnreal Engine provides an Environment Query System (EQS) framework that allows data collection about the virtual environment. AI agents will be able to make informed decisions based on the results.In our behavior tree, we are running an environment query to find a viable target in the Find Random Target task. The query I have created – called EQ_FindTarget – is pretty simple as it just queries the environment looking for instances of the class BP_Target, as shown in Figure 5:Figure 5. The environment queryPawn and ControllerOnce you have created your behavior tree, you will need to execute it through an AIController, the class that is used to possess pawns or characters in order to make them proper AI agents. In the Blueprints folder, you can double-click on the RoboGunController asset to check the pretty self-explanatory code depicted in Figure 6:Figure 6. The character controller codeAs you can see, it’s just a matter of running a behavior tree asset. Easy, isn’t it?If you open the BP_RoboGun asset, you will notice that, in the Details panel, I have set the AI Controller Class to the RoboGunController; this will make the RoboGun pawn be automatically possessed by the RoboGunController.ConclusionThis concludes this brief overview of the behavior tree system; I encourage you to explore the possibilities and more advanced features – such as writing your code the C++ way – by reading my new book “Artificial Intelligence in Unreal Engine 5”; I promise you it will be an informative and, sometimes, funny journey!Author BioMarco Secchi is a freelance game programmer who graduated in Computer Engineering at the Polytechnic University of Milan. He is currently lecturer of the BA in Creative Technologies and of the MA in Creative Media Production. He also mentors BA students in their final thesis projects. In his spare time, he reads (a lot), plays (less than he would like) and practices (to some extent) Crossfit.
Read more
  • 0
  • 0
  • 732

article-image-empowering-modern-graphics-programming-using-vulkan
Preetish Kakkar
04 Nov 2024
10 min read
Save for later

Empowering Modern Graphics Programming using Vulkan

Preetish Kakkar
04 Nov 2024
10 min read
Introduction In the rapidly evolving world of computer graphics, Vulkan has emerged as a powerful and efficient API, revolutionizing how developers approach rendering and compute operations. As the author of "The Modern Vulkan Cookbook," I've had the privilege of diving deep into this technology, exploring its intricacies, and uncovering its potential to solve real-world problems in graphics programming. This book will help you leverage modern graphics programming techniques. You’ll cover a cohesive set of examples that use the same underlying API, discovering Vulkan concepts and their usage in real-world applications.Vulkan, introduced by the Khronos Group in 2016, was designed to address the limitations of older graphics APIs like OpenGL. Its low-overhead, cross-platform nature has made it increasingly popular among developers seeking to maximize performance and gain fine-grained control over GPU resources. One of Vulkan's key strengths lies in its ability to efficiently utilize modern multi-core CPUs and GPUs. By providing explicit control over synchronization and memory management, Vulkan allows developers to optimize their applications for specific hardware configurations, resulting in significant performance improvements. Vulkan Practical Applications Vulkan's impact on solving real-world problems in graphics programming is profound and far-reaching. In the realm of mobile gaming, Vulkan's efficient use of system resources has enabled developers to create console-quality graphics on smartphones, significantly enhancing the mobile gaming experience while conserving battery life. In scientific visualization, Vulkan's compute capabilities have accelerated complex simulations, allowing researchers to process and visualize large datasets in real-time, leading to breakthroughs in fields like climate modeling and molecular dynamics. The film industry has leveraged Vulkan's ray tracing capabilities to streamline pre-visualization processes, reducing production times and costs. In automotive design, Vulkan-powered rendering systems have enabled real-time, photorealistic visualizations of car interiors and exteriors, revolutionizing the design review process. Virtual reality applications built on Vulkan benefit from its low-latency characteristics, reducing motion sickness and improving overall user experience in training simulations for industries like healthcare and aerospace. These practical applications demonstrate Vulkan's versatility in solving diverse challenges across multiple sectors, from entertainment to scientific research and industrial design. Throughout my journey writing "The Modern Vulkan Cookbook," I encountered numerous scenarios where Vulkan's capabilities shine in solving practical challenges: GPU-Driven Rendering: Vulkan's support for compute shaders and indirect drawing commands enables developers to offload more work to the GPU, reducing CPU overhead and improving overall rendering efficiency. This is particularly beneficial for complex scenes with dynamic object counts or procedurally generated geometry. Advanced Lighting and Shading: Vulkan's flexibility in shader programming allows for the implementation of sophisticated lighting models and material systems. Techniques like physically based rendering (PBR) and global illumination become more accessible and performant under Vulkan. Order-Independent Transparency: Achieving correct transparency in real-time rendering has always been challenging. Vulkan's support for advanced rendering techniques, such as A-buffer implementations or depth peeling, provides developers with powerful tools to tackle this issue effectively. Ray Tracing: With the introduction of ray tracing extensions, Vulkan has opened new possibilities for photorealistic rendering in real-time applications. This has profound implications for industries beyond gaming, including architecture visualization and film production. Challenges and Learning Curves Despite its power, Vulkan comes with a steep learning curve. Its verbose nature and explicit control can be daunting for newcomers. During the writing process, I faced the challenge of breaking down complex concepts into digestible chunks without sacrificing depth. This led me to develop a structured approach, starting with core concepts and gradually building up to advanced techniques. One hurdle was explaining the intricacies of Vulkan's synchronization model. Unlike older APIs, Vulkan requires explicit synchronization, which can be a source of confusion and errors for many developers. To address this, I dedicated significant attention to explaining synchronization primitives and their proper usage, providing clear examples and best practices. The Future of Graphics Programming with Vulkan As we look to the future, Vulkan's role in graphics programming is set to grow even further. The API continues to evolve, with new extensions and features being added regularly. Some exciting areas of development include: Machine Learning Integration: The intersection of graphics and machine learning is becoming increasingly important. Vulkan's compute capabilities make it well-suited for implementing ML algorithms directly on the GPU, opening up possibilities for AI-enhanced rendering techniques. Extended Reality (XR): With the rising popularity of virtual and augmented reality, Vulkan's efficiency and low-latency characteristics make it an excellent choice for XR applications. The integration with OpenXR further solidifies its position in this space. Cross-Platform Development: As Vulkan matures, its cross-platform capabilities are becoming more robust. This is particularly valuable for developers targeting multiple platforms, from high-end PCs to mobile devices and consoles. Conclusion Writing "The Modern Vulkan Cookbook" has been an enlightening journey, deepening my appreciation for the power and flexibility of Vulkan. As graphics hardware continues to advance, APIs like Vulkan will play an increasingly crucial role in harnessing this power efficiently. For developers looking to push the boundaries of what's possible in real-time rendering, Vulkan offers a robust toolset. While the learning curve may be steep, the rewards in terms of performance, control, and cross-platform compatibility make it a worthy investment for any serious graphics programmer. Author Bio Preetish Kakkar is a highly experienced graphics engineer specializing in C++, OpenGL, WebGL, and Vulkan. He co-authored "The Modern Vulkan Cookbook" and has extensive experience developing rendering engines, including rasterization and ray-traced pipelines. Preetish has worked with various engines like Unity, Unreal, and Godot, and libraries such as bgfx. He has a deep understanding of the 3D graphics pipeline, virtual/augmented reality, physically based rendering, and ray tracing. 
Read more
  • 0
  • 0
  • 710

article-image-creating-custom-tools-in-unity-automating-repetitive-tasks
Mohamed Essam
17 Oct 2024
5 min read
Save for later

Creating Custom Tools in Unity: Automating Repetitive Tasks

Mohamed Essam
17 Oct 2024
5 min read
Introduction In the fast-paced world of game development, efficiency is key. Developers often find themselves repeating mundane tasks that can consume valuable time and lead to human error. Imagine if you could automate these repetitive tasks, freeing up your time to focus on more creative aspects of your game. In this article, we’ll explore how creating custom tools in Unity can transform your workflow, boost productivity, and reduce the risk of mistakes. Why Custom Tools Matter Custom tools are tailored solutions that address specific needs in your development process. Here’s why they are crucial: Efficiency: Automate routine tasks to save time and reduce manual effort. Consistency: Ensure that repetitive tasks are executed uniformly across your project. Error Reduction: Minimize human errors by automating processes that are prone to mistakes. Focus on Creativity: Spend more time on innovative aspects of your game rather than getting bogged down with repetitive tasks. Creating Your First Custom Tool Overview: We’ll walk through the process of creating a simple Unity editor tool to automate tasks like aligning game objects or batch renaming assets. 1. Setting Up Your Editor Window Define the Purpose: Clearly outline what your tool will accomplish. Create a New Editor Window: Use Unity’s editor scripting API to create a custom window. Add Basic UI Elements: Incorporate buttons, sliders, or input fields to interact with the tool. 2. Implementing Core Functionality Aligning Game Objects: Write scripts to align selected game objects in the scene. Batch Renaming Assets: Create a script that renames multiple assets based on a naming convention. 3. Tips for Effective Custom Tools Start Simple: Begin with a basic tool and gradually add complexity as needed. Prioritize Usability: Ensure your tool is intuitive and easy to use, even for developers who may not be familiar with the script. Document Your Code: Include comments and documentation to make future updates easier. How Custom Tools Solve Common Issues Custom tools address several common development challenges: Repetitive Tasks: Automate repetitive processes like object alignment or asset management to streamline your workflow. Consistency Issues: Ensure that tasks are performed uniformly across your project, avoiding discrepancies and errors. Time Management: Free up time for more complex and creative aspects of your game development by automating mundane tasks. Let's dive into the hands-on section  We've all encountered broken game objects in our scenes, and manually searching through every object to find missing script references can be tedious and time-consuming. One of the key advantages of editor scripts is the ability to create a tool that automatically scans all game objects and pinpoints exactly where the issues are.  Script Dependency Checker . To use this script, simply place it in the Editor folder within your Assets directory. The script needs to be in the Editor directory to function properly. Here's the code that creates a new menu item, which you'll find in the Editor menu bar. What this script does is invoke the CheckDependencies method, which scans all game objects in the scene, checks for any missing components, and collects them in a list. The results are then displayed through the editor window using the OnGUI function. public class ScriptDependencyChecker : EditorWindow {    private static Vector2 scrollPosition;    private static string[] missingScripts = new string[0];    [MenuItem("Tools/Script Dependency Checker")]    public static void ShowWindow()    {        GetWindow<ScriptDependencyChecker>("Script Dependency Checker");    }    private void OnGUI()    {        if (GUILayout.Button("Check Script Dependencies"))        {            CheckDependencies();        }        if (missingScripts.Length > 0)        {            EditorGUILayout.LabelField("Objects with Missing Scripts:", EditorStyles.boldLabel);            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition, GUILayout.Height(300));            foreach (var entry in missingScripts)            {                EditorGUILayout.LabelField(entry);            }            EditorGUILayout.EndScrollView();        }        else        {            EditorGUILayout.LabelField("No missing scripts found.");        }    }    private void CheckDependencies()    {        var missingList = new System.Collections.Generic.List<string>();        GameObject[] allObjects = GameObject.FindObjectsOfType<GameObject>();        foreach (var obj in allObjects)        {            var components = obj.GetComponents<Component>();            foreach (var component in components)            {                if (component == null)                {                    missingList.Add($"Missing script on GameObject: {obj.name}");                }            }        }        missingScripts = missingList.ToArray();    } } Now, let's head over to the Unity Editor and start using this tool. As shown in Image 01, you'll find the Script Dependency Checker under Tools | Script Dependency Checker in the menu bar.  Image 01 - Unity’s menu bar When you click on it, a window will open with a button and a debug section that will display any game objects with missing script references, if found. You can see this in Image 02.  Image 02 - Script dependency window After pressing the button, we discovered a game object named AudioManager with a missing script, as shown in Image 03.  Image 03 - Results of the Checker Next, we can search for AudioManager in the hierarchy and address the issue by either reassigning the missing script or removing it entirely if it's no longer needed, as shown in Image 04.   Image 04 - Game Object with missing script Learning More Explore Unity Documentation: Unity’s official documentation provides comprehensive guides on editor scripting. Join Developer Communities: Engage with forums and communities like the Unity Developer Community or Stack Overflow to exchange ideas and get support. Experiment with Examples: Study and modify existing tools to understand their functionality and apply similar concepts to your projects. Conclusion Creating custom tools in Unity not only enhances your productivity but also ensures a smoother and more efficient development process. As you experiment with building and implementing your tools, consider other repetitive tasks that could benefit from automation. Whether it’s organizing project folders or generating procedural content, the possibilities are endless. By leveraging custom tools, you’ll gain more control over your development environment and focus on what truly matters—bringing your game to life. For more insights into Unity development and custom tools, check out my book, Mastering Unity Game Development with C#: Harness the Full Potential of Unity 2022 Game Development Using C#, where you’ll find in-depth guides and practical examples to further enhance your game development skills.  Author BioMohamed Essam is a highly skilled Unity developer with expertise in creating captivating gameplay experiences across various platforms. With a solid background in game development spanning over four years, he has successfully designed and implemented engaging gameplay mechanics for mobile devices and other platforms. His current focus lies in the development of a highly popular multiplayer game, boasting an impressive 20 million downloads. Equipped with a deep understanding of cutting-edge technologies and a knack for creative problem solving, Mohamed Essam consistently delivers exceptional results in his projects.
Read more
  • 0
  • 0
  • 1148

article-image-five-reasons-to-begin-a-packt-subscription
Packt
12 Nov 2019
1 min read
Save for later

Five reasons to begin a Packt subscription

Packt
12 Nov 2019
1 min read
The Packt library provides you with all the tools you need to stay relevant in tech, whether you’re looking to brush up your PHP skills or take advantage of our learning paths to start from scratch. Here’s our top five reasons to begin a Packt subscription.
Read more
  • 0
  • 0
  • 366
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime