This page has been translated automatically.
Видеоуроки
Интерфейс
Основы
Продвинутый уровень
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Профессиональный уровень (SIM)
Принципы работы
Свойства (properties)
Компонентная Система
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Контроль версий
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World-ноды
Звуковые объекты
Объекты поиска пути
Player-ноды
Программирование
Основы
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Материалы и шейдеры
Rebuilding the Engine Tools
Интерфейс пользователя (GUI)
Двойная точность координат
API
Animations-Related Classes
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
VR-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Учебные материалы

Генерация физических объектов

We need some geometric primitives that the player can move around the Play Area and shoot at. Let's generate them via code.Нам нужны некоторые геометрические примитивы, по которым игрок может перемещаться по игровой площадке и стрелять. Давайте сгенерируем их с помощью кода.

A primitive should have a body and a shape to collide with the Player Character and be affected by gravity. We have implemented interaction with bullets via Intersections at the previous step, so we should set the BulletIntersection bit for the object's Intersection mask.Примитив должен иметь тело (body) и коллизионную форму (shape), чтобы сталкиваться с персонажем игрока и подвергаться воздействию гравитации. Мы реализовали взаимодействие с пулями через Пересечения на предыдущем шаге, поэтому мы должны установить бит BulletIntersection для маски Intersection объекта.

When the robot moves fast and the application framerate is low, the character will be teleported each frame and may go through physical objects due to discrete collision detection. To avoid this we are going to use continuous collision detection.Когда робот движется быстро, а частота кадров приложения низкая, персонаж будет телепортироваться каждый кадр и может проходить через физические объекты из-за дискретного обнаружения столкновений. Чтобы избежать этого, мы собираемся использовать непрерывное обнаружение столкновений.

Примечание
Continuous collision detection is available for sphere and capsule shapes only.Непрерывное обнаружение столкновений доступно только для форм сфера и капсула.
  1. Create a new C# component and call it ObjectGenerator. Copy the following code and save it in your IDE to ensure it's automatic compilation on switching back to UnigineEditor. This component generates the physical objects and places them in the world.Создайте новый компонент C# и назовите его ObjectGenerator. Скопируйте следующий код и сохраните его в вашей IDE, чтобы обеспечить его автоматическую компиляцию при возврате к UnigineEditor. Этот компонент генерирует физические объекты и размещает их в мире.

    ObjectGenerator.cs (C#)
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using Unigine;
    
    [Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
    public class ObjectGenerator : Component
    {
    	private void Init()
    	{
    			// cube 
    			ObjectMeshDynamic box = Primitives.CreateBox(new vec3(1.0f));
    			box.TriggerInteractionEnabled = true;
    			box.SetIntersection(true, 0);
    			box.SetIntersectionMask(0x00000080, 0); // check the BulletIntersection bit
    			box.WorldTransform = MathLib.Translate(new vec3(0.5f, 7.5f, 1.0f));
    			box.SetMaterialPath("materials/mesh_base_0.mat", "*");
    			box.Name = "box";
    			BodyRigid bodyBox = new BodyRigid(box);
    			ShapeBox shapeBox = new ShapeBox(bodyBox, new vec3(1.0f));
    			new ShapeSphere(bodyBox, 0.5f);
    			bodyBox.ShapeBased = false;
    			bodyBox.Mass = 2.0f;
    
    			// sphere
    			ObjectMeshDynamic sphere = Primitives.CreateSphere(0.5f, 9, 32);
    			sphere.TriggerInteractionEnabled = true;
    			sphere.SetIntersection(true, 0);
    			sphere.SetIntersectionMask(0x00000080, 0); // check the BulletIntersection bit
    			sphere.WorldTransform = MathLib.Translate(new vec3(4.5f, 5.5f, 1.0f));
    			sphere.SetMaterialPath("materials/mesh_base_1.mat", "*");
    			sphere.Name = "sphere";
    			BodyRigid bodySphere = new BodyRigid(sphere);
    			new ShapeSphere(bodySphere, 0.5f);
    			bodySphere.ShapeBased = false;
    			bodySphere.Mass = 2.0f;
    
    			// capsule
    			ObjectMeshDynamic capsule = Primitives.CreateCapsule(0.5f, 1.0f, 9, 32);
    			capsule.TriggerInteractionEnabled = true;
    			capsule.SetIntersection(true, 0);
    			capsule.SetIntersectionMask(0x00000080, 0); // check the BulletIntersection bit
    			capsule.WorldTransform = MathLib.Translate(new vec3(4.5f, 0.5f, 3.0f));
    			capsule.SetMaterialPath("materials/mesh_base_2.mat", "*");
    			capsule.Name = "capsule";
    			BodyRigid bodyCapsule = new BodyRigid(capsule);
    			new ShapeCapsule(bodyCapsule, 0.5f, 1.0f);
    			bodyCapsule.ShapeBased = false;
    			bodyCapsule.Mass = 2.0f;
    	}
    }
  2. Switch back to the UnigineEditor and create a new Dummy Node, rename it to "object_generator", and place it somewhere in the world.Переключитесь обратно на UnigineEditor и создайте новую Dummy Node, переименуйте ее в "object_generator" и поместите его где-нибудь в мире.
  3. Attach the created ObjectGenerator component to the "object_generator" node to make it generate physical objects on the initialization.Присоедините созданный компонент ObjectGenerator к ноде "object_generator", чтобы она генерировала физические объекты при инициализации.
  4. Create 3 new materials in the UnigineEditor by choosing Create->Create Material in the Asset Browser. Make them children of the mesh_base material, give them names as specified in the previous code snippet (mesh_base_*), and move them to the data/materials folder of your project (create this folder if it doesn't exist).Создайте 3 новых материала в UnigineEditor, выбрав Create->Create Material в Asset Browser. Сделайте их дочерними элементами материала mesh_base, дайте им имена, указанные в предыдущем фрагменте кода (mesh_base_*), и переместите их в папку data/materials вашего проекта (создайте эту папку, если ее не существует).

  5. Select materials one by one in the Materials window and in the Parameters window switch to the Parameters tab and click on the color field near Albedo to choose different colors for the objects via the color picker.Выберите материалы один за другим в окне Materials, а в окне Parameters переключитесь на вкладку Parameters и нажмите на цветовое поле рядом с Albedo, чтобы выбрать разные цвета для объектов.

  6. Save changes to the world via Ctrl + S.Сохраните изменения в мире с помощью Ctrl + S.
  7. Run the project via the UnigineEditor to see the spawned physical objects in the world.Запустите проект через UnigineEditor, чтобы увидеть созданные физические объекты в мире.
Последнее обновление: 19.04.2024
Build: ()