GUI for Crosshair and Current Game Stats
In games and simulators, the HUD (Heads-Up Display) is used to showcase important information or graphical elements. Our project also requires a HUD, where we will display current game statistics and provide a crosshair to aid the player in shooting. To achieve this, we can obtain the current GUI (Graphical User Interface) and add the required widgets as children. For the crosshair in the center of the screen, we will use WidgetSprite, which enables us to display any image in the UI.
-
Create a HUD.cs component and copy the following code into it:
HUD.cs
using System; using System.Collections; using System.Collections.Generic; using Unigine; [Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- identifier is generated automatically for a new component public class HUD : Component { // crosshair parameters public AssetLink crosshairImage = null; public int crosshairSize = 16; private WidgetSprite sprite = null; private Gui screenGui = null; private ivec2 prev_size = new ivec2(0, 0); private void Init() { // get the current screen GUI screenGui = Gui.GetCurrent(); // add WidgetSprite for the crosshair sprite = new WidgetSprite(screenGui, crosshairImage.AbsolutePath); // set the sprite size sprite.Width = crosshairSize; sprite.Height = crosshairSize; // add the sprite to GUI so that it would always be in the center of the screen and overlap other widgets screenGui.AddChild(sprite, Gui.ALIGN_CENTER | Gui.ALIGN_OVERLAP); // bind the widget lifetime to the world sprite.Lifetime = Widget.LIFETIME.WORLD; } private void Update() { ivec2 new_size = screenGui.Size; if (prev_size != new_size) { screenGui.RemoveChild(sprite); screenGui.AddChild(sprite, Gui.ALIGN_CENTER | Gui.ALIGN_OVERLAP); } prev_size = new_size; } }
-
Create a NodeDummy, place it somewhere in the scene, name it HUD and add the HUD.cs component to it.
-
Add the data/hud/crosshair.png file to the Crosshair Image field.
After compiling and running the application, you should get the following result: