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
Учебные материалы

Создание маршрутов

UNIGINE has a built-in pathfinding system that includes navigation areas, obstacles and functions of the PathRoute class that are used to calculate the optimal routes among obstacles within navigation areas.UNIGINE имеет встроенную систему поиска пути, которая включает в себя навигационные зоны, препятствия и функции класса PathRoute, которые используются для расчета оптимальных маршрутов между препятствиями в навигационных зонах.

Внимание
3D navigation feature is experimental and not recommended for production use.Функция 3D-навигации является экспериментальной и не рекомендуется для использования в финальной сборке.

Via UnigineEditor, you can only add a navigation area (a sector or a mesh) to the scene and place obstacles. The 2D or 3D route that is calculated within the navigation area should be created from the code.С помощью UnigineEditor вы можете только добавить область навигации (сектор или меш) на сцену и разместить препятствия. Двухмерный или трехмерный маршрут, рассчитанный в пределах области навигации, должен быть создан на основе кода.

Creating a Route within Navigation Area
Создание маршрута в пределах области навигации#

To create a route within a navigation area, in which no obstacles are placed, you can use the following:Чтобы создать маршрут в пределах навигационной области, в которой нет препятствий, вы можете использовать следующее:

Исходный код (C++)
// declare points between which a route should be calculated
Unigine::Math::Vec3 p0 = Unigine::Math::Vec3(-60.0f, -60.0f, 5.0f);
Unigine::Math::Vec3 p1 = Unigine::Math::Vec3(60.0f, 60.0f, 5.0f);
Исходный код (C++)
// create a new route
route = PathRoute::create();
// set a radius for the point which will move along the route
route->setRadius(1.2f);
Исходный код (C++)
// create a 3D route
route->create3D(p0,p1);
Примечание
You can create a 2D route the same way by calling the create2D() function.Вы можете создать 2D-маршрут таким же образом, вызвав функцию create2D().

To visualize the calculated route, call the renderVisualizer() function of the PathRoute class:Чтобы визуализировать рассчитанный маршрут, вызовите функцию renderVisualizer() класса PathRoute:

Исходный код (C++)
route->renderVisualizer(vec4(1.0f));

To visualize the navigation area, call the renderVisualizer() functions of the Node class:Чтобы визуализировать область навигации, вызовите функции renderVisualizer() класса Node:

Исходный код (C++)
sector->renderVisualizer();
Примечание
You should enable the engine visualizer by calling Visualizer::setEnabled(1);Необходимо включить визуализатор движка, вызвав Visualizer::setEnabled(1);

You can affect route calculation via UnigineEditor by adjusting parameters of the navigation sector or mesh.Вы можете повлиять на расчет маршрута с помощью UnigineEditor, изменив параметры навигационного сектора или меша.

Creating a Route within Navigation Area with Obstacles
Создание маршрута в пределах навигационной зоны с препятствиями#

Creating the route within a navigation area with obstacles is similar to creating the route within an empty navigation area. Moreover, the route will be recalculated if the obstacle changes its transformation.Создание маршрута в навигационной области с препятствиями аналогично созданию маршрута в пустой навигационной области. Более того, маршрут будет пересчитан, если препятствие изменит свою трансформацию.

If the obstacle is connected with a dynamically changing node that should be bypassed, this node should be set as a parent node for the obstacle. This will enable simultaneous changing transformation of the node and the obstacle. For example:Если препятствие связано с динамически изменяющейся нодой, которую необходимо обойти, эту ноду следует установить в качестве родительской ноды для препятствия. Это обусловит одновременную трансформацию ноды и препятствия. Например:

Исходный код (C++)
#ifndef __APP_WORLD_LOGIC_H__
#define __APP_WORLD_LOGIC_H__

#include <UnigineLogic.h>
#include <UnigineStreams.h>
#include <UnigineObjects.h>
#include <UniginePathFinding.h>

class AppWorldLogic : public Unigine::WorldLogic
{

public:
	AppWorldLogic();
	virtual ~AppWorldLogic();

	int init() override;

	int update() override;
	int postUpdate() override;
	int updatePhysics() override;

	int shutdown() override;

	int save(const Unigine::StreamPtr &stream) override;
	int restore(const Unigine::StreamPtr &stream) override;

private:

	// declare the required variables
	Unigine::ObstacleBoxPtr box_obstacle;
	Unigine::ObjectMeshStaticPtr box;
	Unigine::PathRoutePtr route;

	// declare points between which a route should be calculated
	Unigine::Math::Vec3 p0 = Unigine::Math::Vec3(-60.0f, -60.0f, 5.0f);
	Unigine::Math::Vec3 p1 = Unigine::Math::Vec3(60.0f, 60.0f, 5.0f);

};

#endif // __APP_WORLD_LOGIC_H__
Исходный код (C++)
#include "AppWorldLogic.h"
#include <UnigineEditor.h>
#include <UnigineGame.h>
#include <UnigineVisualizer.h>
#include <UnigineLog.h>

using namespace Unigine;
using namespace Math;

// World logic, it takes effect only when the world is loaded.
// These methods are called right after corresponding world script's (UnigineScript) methods.

AppWorldLogic::AppWorldLogic()
{
}

AppWorldLogic::~AppWorldLogic()
{
}

int AppWorldLogic::init()
{
	// enable the engine visualizer
	Visualizer::setEnabled(1);

	// create a navigation sector within which pathfinding will be performed
	NavigationSectorPtr navigation = NavigationSector::create(vec3(128.0f, 128.0f, 8.0f));
	navigation->setWorldTransform(translate(Vec3(1.0f, 1.0f, 5.0f)));

	// create the ObjectMeshStatic that should be bypassed
	box = ObjectMeshStatic::create("core/meshes/box.mesh");
	box->setPosition(Vec3(2.0f, 2.2f, 1.5f));
	box->setScale(vec3(2.0f, 2.0f, 2.0f));

	// create an obstacle
	box_obstacle = ObstacleBox::create(vec3(1.2f, 1.2f, 1.2f));
	box_obstacle->setPosition(Vec3(0.0f, 0.0f, 0.0f));

	// add the obstacle as the child node to the mesh in order to change their transformation simultaneously
	box->addChild(box_obstacle);

	// create a new route
	route = PathRoute::create();
	// set a radius for the point which will move along the route
	route->setRadius(1.2f);

	return 1;
}

////////////////////////////////////////////////////////////////////////////////
// start of the main loop
////////////////////////////////////////////////////////////////////////////////

int AppWorldLogic::update()
{
	// get the frame duration
	float ifps = Game::getIFps();
	// and define the angle of the object's rotation
	float angle = ifps * 90.0f;

	// change transformation of the mesh
	box->setTransform(box->getTransform() * Mat4(rotateZ(angle)));
	// render the bounding box of the obstacle
	box_obstacle->renderVisualizer();

	// recalculate the route in the current frame and render its visualizer
	route->create2D(p0, p1);
	if (route->isReached()) route->renderVisualizer(vec4(1.0f));
	else Log::message("PathRoute failed"); 
	
	return 1;
}

int AppWorldLogic::postUpdate()
{
	// The engine calls this function after updating each render frame: correct behavior after the state of the node has been updated.
	return 1;
}

int AppWorldLogic::updatePhysics()
{
	// Write here code to be called before updating each physics frame: control physics in your application and put non-rendering calculations.
	// The engine calls updatePhysics() with the fixed rate (60 times per second by default) regardless of the FPS value.
	// WARNING: do not create, delete or change transformations of nodes here, because rendering is already in progress.
	return 1;
}

////////////////////////////////////////////////////////////////////////////////
// end of the main loop
////////////////////////////////////////////////////////////////////////////////

int AppWorldLogic::shutdown()
{
	// Write here code to be called on world shutdown: delete resources that were created during world script execution to avoid memory leaks.
	return 1;
}

int AppWorldLogic::save(const Unigine::StreamPtr &stream)
{
	// Write here code to be called when the world is saving its state (i.e. state_save is called): save custom user data to a file.
	UNIGINE_UNUSED(stream);
	return 1;
}

int AppWorldLogic::restore(const Unigine::StreamPtr &stream)
{
	// Write here code to be called when the world is restoring its state (i.e. state_restore is called): restore custom user data to a file here.
	UNIGINE_UNUSED(stream);
	return 1;
}
Примечание
In the example above, the route is recalculated each frame. However, it is non-optimal for application performance. You can calculate the route, for example, once per 10 frames.В приведенном выше примере маршрут пересчитывается для каждого кадра. Однако это неоптимально для производительности приложения. Вы можете рассчитать маршрут, например, один раз за 10 кадров.

As a result, you will have a simple navigation sector, in which the dynamically changing obstacle box is placed.В результате у вас получится простой навигационный сектор, в котором размещен динамически изменяющийся блок препятствий.

Here the obstacle is highlighted with redЗдесь препятствие выделено красным цветом
Последнее обновление: 28.05.2024
Build: ()