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

Интерактивная зона

In games and VR applications, some actions are performed when you enter a specific area in the scene (for example, music starts, sound or visual effects appear). Let's implement this in our project: when you enter or teleport to a certain area, it rains inside it.В играх и VR-приложениях часто бывает нужно при вхождении пользователя в определенную область сцены выполнять определенные действия (например, включать музыку, звуковые или визуальные эффекты). В нашем проекте давайте сделаем так, чтобы при входе или телепортировании пользователя в определенную область, в ее пределах шел дождь.

In UNIGINE, the World Trigger node is used to track when any node (collider or not) gets inside or outside of it (for objects with physical bodies, the Physical Trigger node is used).В UNIGINE для отслеживания вхождения любой ноды (не важно, с физическим телом или без) в определенный объем и покидания этого объема используется World Trigger (для объектов с физическим телом используется Physical Trigger).

  1. First of all, create a trigger to define the rain area. On the Menu bar, choose Create -> Logic -> World Trigger and place the trigger near the Material Ball, for example. Set the trigger size to (2, 2, 2).Первым делом создадим триггер для определения области, где будем делать дождь. Выберите в меню Create -> Logic -> World Trigger и расположите триггер, например, рядом с Material Ball. Установите размеры триггера (2, 2, 2).

  2. Create a new TriggerZone component that will turn the rain node on and off (in our case, it is a particle system simulating rain), depending on the trigger state. Add the following code to the component and then assign it to the World Trigger node:Создайте новый компонент TriggerZone, который в зависимости от состояния триггера будет включать или выключать заданную ноду (в нашем случае это будет система частиц имитирующая дождь). Добавьте в компонент следующий код и затем назначьте этот компонент на ноду World Trigger:

    Исходный код (C#)
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Unigine;
    
    [Component(PropertyGuid = "AUTOGEN_GUID")] // <-- идентификатор генерируется автоматически для компонента
    public class TriggerZone : Component
    {
    	private WorldTrigger trigger = null;
    	public Node ControlledNode = null;
    	private void Init()
    	{
    		// проверяем что компонент назначен на ноду WorldTrigger
    		if (node.Type != Node.TYPE.WORLD_TRIGGER)
    		{
    			Log.Error($"{nameof(TriggerZone)} error: this component can only be assigned to a WorldTrigger.\n");
    			Enabled = false;
    			return;
    		}
    		// проверяем указана ли управляемая нода 'ControlledNode'
    		if (ControlledNode == null)
    		{
    			Log.Error($"{nameof(TriggerZone)} error: 'ControlledNode' is not set.\n");
    			Enabled = false;
    			return;
    		}
    		// устанавливаем функции, которые будут вызываться при входе произвольной ноды в объем триггера и покидании его
    		trigger = node as WorldTrigger;
    		trigger.EventEnter.Connect(trigger_enter);
    		trigger.EventLeave.Connect(trigger_leave);
    	}
    	
    	private void Update()
    	{
    		// write here code to be called before updating each render frame
    		
    	}
    
    	// функция, включающая ноду ControlledNode при вхождении игрока (нода 'vr_player') в триггер
    	private void trigger_enter(Node node)
    	{
    		ControlledNode.Enabled = true;
    	}
    	// функция, выключающая ноду ControlledNode при покидании триггера игроком (нода 'vr_player')
    	private void trigger_leave(Node node)
    	{
    		if (node.Name != "vr_player")
    			return;
    		ControlledNode.Enabled = false;
    	}
    }
  3. Now, let's add the rain effect. Drag the rain_effect.node asset from the vr/particles folder of the UNIGINE Starter Course Project add-on to the scene, add it as the child to the trigger node and turn it off (the component will turn it on later).Теперь добавим эффект дождя. Найдите ассет rain_effect.node (data/vr/particles в UNIGINE Starter Course Project), перетащите его в сцену и добавьте в качестве дочерней ноды к триггеру и отключите пока (ее будет включать наш компонент).

  4. Drag the rain_effect node from the World Hierarchy window to the Controlled Node field of the TriggerZone (in the Parameters window).Затем перетащите ноду rain_effect из World Hierarchy в поле Controlled Node компонента TriggerZone.

  5. Select the vr_player (PlayerDummy) node in the World Hierarchy and check the Triggers Interaction option for it to make the trigger react on contacting it.Выделите ноду vr_player (PlayerDummy) в World Hierarchy и включите для нее опцию Triggers Interaction чтобы триггер на нее реагировал.

  6. Save changes (Ctrl+S), click Play to run the application, and try to enter the area defined by the trigger — it is raining inside.Сохраните мир (Ctrl+S), запустите проект, нажав кнопку Play, и попробуйте войти в заданную область – в ней будет локальный дождь.

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