This page has been translated automatically.
Основы UNIGINE
1. Введение
2. Виртуальные миры и работа с ними
3. Подготовка 3D моделей
4. Материалы
5. Камеры и освещение
6. Реализация логики приложения
7. Создание кат-сцен и запись видео
8. Подготовка проекта к релизу
9. Физика
10. Основы оптимизации
12. ПРОЕКТ3: Аркадная гонка по пересеченной местности от 3-го лица
13. ПРОЕКТ4: VR приложение с простым взаимодействием
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

GUI для прицела и текущей игровой статистики

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.В играх, да и в симуляторах, для отображения нужной информации или каких-либо графических элементов используется так называемый HUD (Heads-Up Display). В нашем проекте такой тоже понадобится, на нем мы будем отображать текущую игровую статистику, а также рисовать прицел, чтобы игроку было удобнее стрелять. Для того, чтобы это сделать, нам достаточно получить текущий графический интерфейс (GUI: Graphical User Interface), а затем добавить к нему нужные виджеты в качестве дочерних элементов. Для прицела в центре экрана будем использовать WidgetSprite, который позволяет отображать в UI любое изображение.

  1. Create a HUD.cs component and copy the following code into it:Create a HUD.cs component and copy the following code into it:

    HUD.csHUD.cs

    Исходный код (C#)
    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 HUD.cs component and copy the following code into it:HUD.cs

    Create a HUD.cs component and copy the following code into it:Создайте компонент HUD.cs и скопируйте в него следующий код:

    HUD.csHUD.cs

    Исходный код (C#)
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Unigine;
    
    [Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- идентификатор генерируется автоматически для нового компонента
    public class HUD : Component
    {
        // параметры прицела
        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()
        {
    		// получаем текущий экранный GUI
    		screenGui = Gui.GetCurrent();
    
    		// создаем виджет WidgetSprite для прицела
    		sprite = new WidgetSprite(screenGui, crosshairImage.AbsolutePath);
    		// задаем размер спрайта
    		sprite.Width = crosshairSize;
    		sprite.Height = crosshairSize;
    
    		// добавляем спрайт к GUI так, чтобы он всегда был посередине экрана и поверх всех остальных виджетов
    		screenGui.AddChild(sprite, Gui.ALIGN_CENTER | Gui.ALIGN_OVERLAP);
    		// привязываем время жизни виджета к миру
    		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;
        }
    }
  2. Create a NodeDummy, place it somewhere in the scene, name it HUD and add the HUD.cs component to it.Create a NodeDummy, place it somewhere in the scene, name it HUD and add the HUD.cs component to it.

    Create a NodeDummy, place it somewhere in the scene, name it HUD and add the HUD.cs component to it.

    Create a NodeDummy, place it somewhere in the scene, name it HUD and add the HUD.cs component to it.Создайте NodeDummy, поместите его где-нибудь в сцене, назовите его HUD и добавьте к нему компонент HUD.cs.

  3. Add the data/hud/crosshair.png file to the Crosshair Image field.Добавьте файл data/hud/crosshair.png в поле Crosshair Image.

After compiling and running the application, you should get the following result:В итоге, после компиляции и запуска приложения должен получиться такой результат:

Последнее обновление: 04.04.2024
Build: ()