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

Пересечения (Intersections)

Unigine has different methods to detect intersections. Intersection is a shared point of the defined area (or line) and an object. This article describes different types of intersections and their usage.Unigine имеет различные методы для обнаружения пересечений. Пересечение - это общая точка определенной области (или линии) и объекта. В этой статье описываются различные типы пересечений и их использование.

There are three main types of intersections:Существует три основных типа пересечений:

  • World intersection — an intersection with objects and nodes.World intersection — пересечение с объектами и нодами .
  • Physics intersection — an intersection with shapes and collision objects.Physics intersection — пересечение с фигурами и объектами столкновения .
  • Game intersection — an intersection with pathfinding nodes such as obstacles.Game intersection — пересечение с нодами поиска пути, такими как препятствия.

The Shape and Object classes have their own getIntersection() functions. These functions are used to detect intersections with a specific shape or a specific surface of the object.Классы Shape и Object имеют свои собственные функции getIntersection(). Эти функции используются для обнаружения пересечений с определенной формой или определенной поверхностью объекта.

See Also
See Also
#

  • C# Component Sample demonstrating the use of World IntersectionДемонстрационный проект C# Component Sample, который демонстрирует использование World Intersection.
  • C++ Sample demonstrating different cases of intersection detectionДемонстрационный проект C++ Sample, который показывает различные варианты определения пересечений.

World Intersection
Пересечения World Intersection
#

By using different overloaded World class getIntersection() functions you can find objects and nodes that intersect bounds of the specified bounding volume or identify the first intersection of the object with the invisible tracing line.Используя различные перегруженные функции World класса getIntersection(), вы можете находить объекты и ноды, которые пересекают границы указанного ограничивающего объема, или определять первое пересечение объекта с невидимой линией трассировки.

The World class functions for intersection search can be divided into 3 groups:Функции класса World для поиска пересечений можно разделить на 3 группы:

Примечание

The following objects have individual parameters that control the accuracy of intersection detection:Следующие объекты имеют индивидуальные параметры, которые контролируют точность обнаружения пересечений:

Intersection with Nodes
Пересечения с нодами
#

To find the intersection of nodes with bounds of the specified volume, you should use functions that have a bounding volume and a vector of nodes in arguments:Чтобы найти пересечение нод с границами указанного объема, вы должны использовать функции, которые имеют ограничивающий объем и вектор нод в аргументах:

Schematic visual representation of intersection with nodes in bounding volumeСхематическое визуальное представление пересечения с нодами в ограничивающем объеме

These functions return the value indicating the result of the intersection search: true if the intersection was found; otherwise, false. Intersected nodes can be found in the collection that passed as an argument to the function.Эти функции возвращают значение, указывающее результат поиска пересечения: true, если пересечение было найдено; в противном случае false. Пересеченные ноды можно найти в коллекции, переданной в качестве аргумента функции.

To clarify the nodes search, specify the type of node to search.Чтобы уточнить поиск, укажите тип нод для поиска.

Usage Example
Пример использования
#

In the example below, the engine checks intersections with a bounding box and shows the names of intersected objects in the console.В приведенном ниже примере движок проверяет пересечения с помощью ограничительной рамки и показывает имена пересекающихся объектов в консоли.

In the Init() function the bounding box is defined.В функции Init() определяется ограничивающая рамка.

The main logic is in the Update() method, the engine checks the intersection and shows the message about intersection.Основная логика заключается в методе Update(), движок проверяет пересечение и показывает сообщение о пересечении.

Исходный код (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

#region Math Variables
#if UNIGINE_DOUBLE
using Scalar = System.Double;
using Vec3 = Unigine.dvec3;
#else
using Scalar = System.Single;
using Vec3 = Unigine.vec3;
using WorldBoundBox = Unigine.BoundBox;
#endif
#endregion

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class Intersections : Component
{

	// define a bounding box
	WorldBoundBox boundBox;

	// create a counter to show the message once
	int counter = 1;

	private void Init()
	{

		// initialize the bounding box
		boundBox = new WorldBoundBox(new Vec3(0.0f), new Vec3(10.0f));

	}

	private void Update()
	{

		// check the intersection with the bounding box
		List<Node> nodes = new List<Node>();
		bool result = World.GetIntersection(boundBox, nodes);
		if (result && counter !=0)
		{
			foreach(Node n in nodes)
			{
				// show the name of the intersected node in the console
				Log.Message("There was an intersection with: {0} \n", n.Name);
			}
			counter--;
		}

	}

}

Intersection with Objects
Пересечения с объектами
#

The following functions can be used to perform the intersection search with objects:Для выполнения поиска пересечений с объектами можно использовать следующие функции:

Schematic visual representation of intersection with objects in bounding volumeСхематическое визуальное представление пересечения с объектами в ограничивающем объеме

These functions return the value indicating the result of the intersection search: true if the intersection was found; otherwise, false. You can pass the start (vec3 p0) and the end (vec3 p1) point of the intersecting line or pass the (BoundBox, BoundFrustum, BoundSphere) to get the intersection of objects with a line or with a bounding volume, respectively. Intersected nodes can be found in the collection that passed as an argument to the function.Эти функции возвращают значение, указывающее результат поиска пересечения: true, если пересечение было найдено; в противном случае, false. Вы можете передать начальную (vec3 p0) и конечную (vec3 p1) точки пересекающей линии или передать (BoundBox, BoundFrustum, BoundSphere), чтобы получить пересечение объектов с линией или с ограничивающим объемом соответственно. Пересеченные ноды можно найти в коллекции, переданной в качестве аргумента функции.

For WorldBoundFrustum, there are two modes of getting intersections:Для WorldBoundFrustum существует два способа получения пересечений:

  • Intersections with the objects that are visible inside the frustum — GetVisibleIntersection()Пересечения с объектами, которые видны внутри пирамиды видимости — GetVisibleIntersection()
  • Intersections with all objects inside the frustum, both visible and invisibleGetIntersection()Пересечения со всеми объектами внутри пирамиды видимости, как видимыми, так и невидимымиGetIntersection()

Finding Objects Intersected by a Bounding Box
Поиск объектов, пересекаемых ограничивающим прямоугольником (box)
#

In the example below, the engine checks intersections with a bounding box and shows the message in the console.В приведенном ниже примере движок проверяет пересечения с помощью ограничительной рамки и отображает сообщение в консоли.

In the Init() function the bounding box is defined.В функции Init() определяется ограничивающая рамка.

The main logic is in the Update() method, the engine checks the intersection and shows the message about intersection.Основная логика заключается в методе Update(), движок проверяет пересечение и показывает сообщение о пересечении.

Исходный код (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

#region Math Variables
#if UNIGINE_DOUBLE
using Scalar = System.Double;
using Vec3 = Unigine.dvec3;
#else
using Scalar = System.Single;
using Vec3 = Unigine.vec3;
using WorldBoundBox = Unigine.BoundBox;
#endif
#endregion

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class Intersections : Component
{

	// define a bounding box
	WorldBoundBox boundBox;

	// create a counter to show the message once
	int counter = 1;

	private void Init()
	{

		// initialize the bounding box
		boundBox = new WorldBoundBox(new Vec3(0.0f), new Vec3(10.0f));

	}

	private void Update()
	{

		// check the intersection with the bounding box
		List<Unigine.Object> objects = new List<Unigine.Object>();
		bool result = World.GetIntersection(boundBox, objects);
		if (result && counter != 0)
		{
			foreach (Unigine.Object o in objects)
			{
				Log.Message("There was an intersection with: {0} \n", o.Name);
			}
			counter--;
		}
	}

}

Finding Objects Intersected by a Bounding Frustum
Поиск объектов, пересекаемых ограничивающей пирамидой видимости (frustum)
#

For WorldBoundFrustum, there are two modes of getting intersections:Для WorldBoundFrustum существует два способа получения пересечений:

  • Intersections with the objects that are visible inside the frustum (within the rendering visibility distance and the object's LOD is visible by the camera) — GetVisibleIntersection()Пересечения с объектами, которые видны внутри пирамиды видимости (в пределах расстояния видимости рендеринга и LOD объекта виден камерой) — GetVisibleIntersection()
  • Intersections with all objects inside the frustum, both visible and invisible (either occluded by something or out of the visibility distance) — GetIntersection()Пересечения со всеми объектами внутри пирамиды видимости, как видимыми, так и невидимыми (либо закрытыми чем—то, либо вне пределов видимости) - GetIntersection()

In the example below, the engine checks intersections of WorldBoundFrustum with all objects, both visible and invisible. The frustum itself is highlighted blue, and the objects that are inside the frustum are highlighted red for 20 seconds.В приведенном ниже примере движок проверяет пересечения WorldBoundFrustum со всеми объектами, как видимыми, так и невидимыми. Сама пирамида видимости подсвечивается синим цветом, а объекты, находящиеся внутри пирамиды видимости, подсвечиваются красным в течение 20 секунд.

Исходный код (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

#region Math Variables
#if UNIGINE_DOUBLE
using Scalar = System.Double;
using Vec3 = Unigine.dvec3;
#else
using Scalar = System.Single;
using Vec3 = Unigine.vec3;
using WorldBoundBox = Unigine.BoundBox;
#endif
#endregion

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class Intersections : Component
{

	private void Init()
	{

		// enable the visualizer
		Visualizer.Enabled = true;

	}

	private void Update()
	{

		if(Input.IsKeyDown(Input.KEY.SPACE))
		{
			// get a reference to the camera
			Player player = Game.Player;
			Camera camera = player.Camera;

			// get the size of the current application window
			EngineWindow main_window = WindowManager.MainWindow;
			if (!main_window)
			{
				Engine.Quit();
				return;
			}

			ivec2 main_size = main_window.Size;

			mat4 projection = camera.GetAspectCorrectedProjection(((float)(main_size.y) / ((float)main_size.x)));

			// bound frustrum for the intersection and a list to store intersected objects
			var bf = new WorldBoundFrustum(camera.Projection, camera.Modelview);
			Visualizer.RenderFrustum(projection, camera.IModelview, vec4.BLUE, 20.0f);
			
			List<Unigine.Object> objects = new List<Unigine.Object>();

			// perform the intersection search with the bound frustrum
			World.GetIntersection(bf, objects);

			// draw the bound spheres of all objects' surfaces found by the search
			foreach(var obj in objects)
			{
				for (int i = 0; i < obj.NumSurfaces; ++i)
					{
						var bs = obj.GetBoundSphere(i);
						Visualizer.RenderBoundSphere(bs, obj.WorldTransform, vec4.RED, 20.0f);
					}
			}
			
		}

	}

}

To search only for intersections with the objects that are within the rendering visibility distance and the LODs of which are visible, use the following method instead of getIntersection():Для поиска только пересечений с объектами, которые находятся в пределах расстояния видимости визуализации и LOD которых видны, используйте следующий метод вместо getIntersection():

Исходный код (C#)
// perform the intersection search with the bound frustrum
World.GetVisibleIntersection(player.WorldPosition, bf, objects, 100.0f);
Примечание
The current rendering Distance Scale is also taken into account in the distance calculation.Текущее значение рендеринга Distance Scale также учитывается при расчете расстояния.

First Intersected Object
Поиск первого объекта, пересеченного линией
#

The following functions are used to find the nearest intersected object with the traced line. You should specify the start point and the end point of the line, and the function detects if there are any object on the way of this line.Следующие функции используются для поиска ближайшего объекта, пересекающегося с линией трассировки. Вы должны указать начальную точку и конечную точку линии, и функция определит, есть ли какие-либо объекты на пути этой линии.

Schematic visual representation of intersection with objects and traced lineСхематическое визуальное представление пересечения с объектами и линией трассировки

These functions return an intersection information and a pointer to the nearest object to the start point (p0). Information about the intersection can be presented in standard vectors or in the following format that you pass to functions as arguments:Эти функции возвращают информацию о пересечении и указатель на ближайший объект к начальной точке (p0). Информация о пересечении может быть представлена в стандартных векторах или в следующем формате, который вы передаете функциям в качестве аргументов:

  • WorldIntersection intersection — the WorldIntersection class instance. By using this class you can get the intersection point (coordinates), the index of the intersected triangle of the object and the index of the intersected surface.WorldIntersection intersection — экземпляр класса WorldIntersection. Используя этот класс, вы можете получить точку пересечения (координаты), индекс пересекаемого треугольника объекта и индекс пересекаемой поверхности.
  • WorldIntersectionNormal normal — the WorldIntersectionNormal class instance. By using this class you can get only the normal of the intersection point.WorldIntersectionNormal normal — экземпляр класса WorldIntersectionNormal. Используя этот класс, вы можете получить только нормаль точки пересечения.
  • WorldIntersectionTexCoord texcoord — the WorldIntersectionTexCoord class instance. By using this class you can get only the texture coordinates of the intersection point.WorldIntersectionTexCoord texcoord — экземпляр класса WorldIntersectionTexCoord. Используя этот класс, вы можете получить только текстурные координаты точки пересечения.

These functions detect intersection with surfaces (polygons) of meshes. But there are some conditions to detect the intersection with the surface:Эти функции обнаруживают пересечение с поверхностями (полигонами) сеток. Но есть некоторые условия для обнаружения пересечения с поверхностью:

  1. The surface is enabled.Поверхность включена.
  2. The surface has a material assigned.Поверхности присвоен материал.
  3. Per-surface Intersection flag is enabled.Для каждой поверхности включен флаг Intersection.

    Примечание
    You can set this flag to the object's surface by using the Object.SetIntersection() function.Вы можете установить этот флаг на поверхность объекта с помощью функции Object.SetIntersection().

To clarify the object search, perform the following:Чтобы уточнить поиск объекта, выполните следующие действия:

  • Use an Intersection mask. An intersection is found only if an object is matching the Intersection mask.Используйте маску Intersection. Пересечение обнаруживается только в том случае, если объект соответствует маске Intersection.
  • Specify the list of objects (nodes) to exclude and pass to the function as an argument.Укажите список объектов (нод) для исключения и передачи функции в качестве аргумента.

Usage Example
Пример использования
#

In the example below, the engine checks intersections with a raytraced line and shows the message in the console.В приведенном ниже примере движок проверяет пересечения с линией трассировки и отображает сообщение в консоли.

Исходный код (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

#region Math Variables
#if UNIGINE_DOUBLE
using Scalar = System.Double;
using Vec3 = Unigine.dvec3;
#else
using Scalar = System.Single;
using Vec3 = Unigine.vec3;
#endif
#endregion

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class Intersections : Component
{

	// define world intersection instance
	WorldIntersection wi;

	// create a counter to show the message once
	int counter = 1;

	private void Init()
	{

		// initialize the world intersection
		wi = new WorldIntersection();

	}

	private void Update()
	{

		// check the intersection with the object
		Unigine.Object o = World.GetIntersection(new Vec3(0.0f), new Vec3(1.0f), 1, wi);
		if (o != null && counter != 0)
		{
			Log.Message("The name of the obstacle is: {0} \n", o.Name);
			counter--;
		}
	}

}

Physics Intersection
Пересечения Physics Intersection
#

Physics intersection function detects intersections with a physical shape or a Fracture Body. If the object has no body, this function detects intersection with surfaces (polygons) of the object having the Physics Intersection flag enabled. When you need to find the intersection with the shape of the object (not with polygons), the intersection function of Physics class is the best way to get it.Функция физического пересечения обнаруживает пересечения с физической формой (shape) или Fracture Body. Если объект не имеет тела, эта функция обнаруживает пересечение с поверхностями (полигонами) объекта с включенным флагом Physics Intersection. Когда вам нужно найти пересечение с формой (shape) объекта (не с полигонами), функция пересечения класса Physics - лучший способ ее получить.

The picture above shows how the GetIntersection() function detects the shape that intersects with the lineНа рисунке выше показано, как функция GetIntersection() определяет форму (shape), которая пересекается с линией

There are 4 functions to find physics intersections:Есть 4 функции для поиска пересечений физики:

These functions perform tracing from the start p0 point to the end p1 point to find a collision object (or a shape) located on that line. Functions use world space coordinates.Эти функции выполняют трассировку от начальной точки p0 до конечной точки p1, чтобы найти коллизионный объект (или форму), расположенный на этой линии. Функции используют координаты мирового пространства.

Thus, to exclude some obstacles you should use these methods:Таким образом, чтобы исключить некоторые препятствия, вы должны использовать эти методы:

  • Use a Physics Intersection mask. A physics intersection is detected only if the Physics Intersection mask of the surface/shape/body matches the Intersection mask passed as a function argument, otherwise it is ignored.Используйте маску Physics Intersection. Физическое пересечение обнаруживается только в том случае, если маска Physics Intersection поверхности/формы/тела совпадает с маской Intersection, переданной в качестве аргумента функции, в противном случае она игнорируется.
  • Specify the list of objects to exclude and pass to the function as an argument.Укажите список объектов для исключения и передачи функции в качестве аргумента.

Usage Example
Пример использования
#

The following example shows how you can get the intersection information by using the PhysicsIntersection class. In this example we specify a line from the point of the camera (vec3 p0) to the point of the mouse pointer (vec3 p1). The executing sequence is the following:В следующем примере показано, как вы можете получить информацию о пересечении с помощью класса PhysicsIntersection. В этом примере мы задаем линию от точки камеры (vec3 p0) до точки указателя мыши (vec3 p1). Последовательность выполнения следующая:

  1. Define and initialize two points (p0 and p1) by using the Player.GetDirectionFromScreen() function.Определите и инициализируйте две точки (p0 и p1) с помощью функции Player.GetDirectionFromScreen().
  2. Create an instance of the PhysicsIntersection class to get the intersection information.Создайте экземпляр класса PhysicsIntersection, чтобы получить информацию о пересечении.
  3. Check if there is an intersection with an object with a shape or a collision object. The GetIntersection() function returns an intersected object when the object intersects with the traced line.Проверьте, есть ли пересечение с объектом с формой или объектом столкновения. Функция GetIntersection() возвращает пересеченный объект, когда объект пересекается с линией трассировки.
  4. When the object intersects with the traced line, all surfaces of the intersected object change their material parameters. If the object has a shape, its information will be shown in console. The PhysicsIntersection class instance gets the coordinates of the intersection point and the Shape class object. You can get all these fields by using Shape, Point properties.Когда объект пересекается с линией трассировки, все поверхности пересекаемого объекта изменяют свои материальные параметры. Если объект имеет форму, его информация будет отображена в консоли. Экземпляр класса PhysicsIntersection получает координаты точки пересечения и объекта класса Shape. Вы можете получить все эти поля, используя свойства Shape, Point.
Исходный код (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

#if UNIGINE_DOUBLE
    using Vec3 = Unigine.dvec3;
    using Vec4 = Unigine.dvec4;
    using Mat4 = Unigine.dmat4;
#else
    using Vec3 = Unigine.vec3;
    using Vec4 = Unigine.vec4;
    using Mat4 = Unigine.mat4;
#endif

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class PhysicsIntersectionClass : Component
{
	private void Init()
	{
		// create a mesh instance with a box surface
		Mesh mesh = new Mesh();
		mesh.AddBoxSurface("box", new vec3(2.2f));
		
		// create a new dynamic mesh from the Mesh instance
		ObjectMeshDynamic dynamic_mesh = new ObjectMeshDynamic(mesh);

		dynamic_mesh.WorldTransform = MathLib.Translate(new Vec3(0.0f, 0.0f, 2.0f));

		// assign a body and a shape to the dynamic mesh
		BodyRigid body = new BodyRigid(dynamic_mesh);
		ShapeBox shape = new ShapeBox(body, new vec3(2.2f));
	}
	private void Update()
	{
		// initialize points of the mouse direction
		Vec3 p0, p1;

		// get the current player (camera)
		Player player = Game.Player;
			
		// get the size of the current application window
		EngineWindow main_window = WindowManager.MainWindow;
		if (!main_window)
		{
			Engine.Quit();
			return;
		}

		ivec2 main_size = main_window.Size;

		// get the current X and Y coordinates of the mouse pointer
		int mouse_x = Gui.GetCurrent().MouseX;
		int mouse_y = Gui.GetCurrent().MouseY;
		// get the mouse direction from the player's position (p0) to the mouse cursor pointer (p1)
		player.GetDirectionFromScreen(out p0, out p1, mouse_x, mouse_y, 0, 0, main_size.x, main_size.y);

		// create the instance of the PhysicsIntersection object to save the information about the intersection
		PhysicsIntersection intersection = new PhysicsIntersection();
		// get an intersection
		Unigine.Object obj = Physics.GetIntersection(p0, p1, 1, intersection);

		// if the intersection has occurred, change the parameter of the object's material    
		if (obj != null)
		{
			for (int i = 0; i < obj.NumSurfaces; i++)
			{
				obj.SetMaterialParameterFloat4("albedo_color", new vec4(1.0f, 1.0f, 0.0f, 1.0f), i);
			}

			// if the intersected object has a shape, show the information about the intersection   
			Shape shape = intersection.Shape;
			if (shape != null)
			{
				Log.Message("physics intersection info: point: ({0} {1} {2}) shape: {3}\n", intersection.Point.x, intersection.Point.y, intersection.Point.z, shape.TypeName);
			}
		}
		
	}
}

Game Intersection
Пересечения Game Intersection
#

The GetIntersection() functions of the Game class are used to check the intersection with obstacles (pathfinding nodes):Функции GetIntersection() класса Game используются для проверки пересечения с препятствиями (нодами поиска пути):

The engine creates an invisible cylinder with specified radius between two points and checks if an obstacle is inside it.Двигатель создает невидимый цилиндр с заданным радиусом между двумя точками и проверяет, находится ли внутри него препятствие.

Schematic visual representation of intersection with objects and cylinder volumeСхематическое визуальное представление пересечения с объектами и объемом цилиндра

These functions return an intersection information and a pointer to the nearest obstacle to the start point (p0). Information about the intersection will be presented in the GameIntersection class instance which you pass to the function as an argument or in the vector.Эти функции возвращают информацию о пересечении и указатель на ближайшее препятствие к начальной точке ( p0). Информация о пересечении будет представлена в экземпляре класса GameIntersection, который вы передаете функции в качестве аргумента или в векторе.

Use the mask and exclude arguments of the overloaded function to specify the obstacle search.Используйте аргументы маски и исключения перегруженной функции, чтобы указать поиск препятствий.

To clarify the obstacle search, perform the following:Чтобы уточнить поиск препятствий, выполните следующие действия:

  • Use an obstacle Intersection mask. An intersection is found only if an object is matching the Intersection mask, otherwise it is ignored.Используйте маску препятствия Intersection. Пересечение обнаруживается только в том случае, если объект соответствует маске Intersection, в противном случае оно игнорируется.
  • Specify the list of obstacles to exclude and pass to the function as an argument.Укажите список препятствий для исключения и передачи функции в качестве аргумента.

Usage Example
Пример использования
#

The following example shows how you can get the intersection point (vec3) of the cylinder between two points with an obstacle. We'll do the following:В следующем примере показано, как вы можете получить точку пересечения (vec3) цилиндра между двумя точками с препятствием. Мы сделаем следующее:

  1. Create an instance of the ObstacleBox class on the application initialization.Создайте экземпляр класса ObstacleBox при инициализации приложения.
  2. Define two points (p1 and p2) that specify the beginning and the end of the cylinder.Определите две точки (p1 и p2), которые определяют начало и конец цилиндра.
  3. Create an instance of the GameIntersection class to get the intersection point coordinates.Создайте экземпляр класса GameIntersection, чтобы получить координаты точки пересечения.
  4. Check if there is an intersection with an obstacle. The Game::getIntersection() function returns an intersected obstacle when the obstacle appears in the area of the cylinder.Проверьте, есть ли пересечение с препятствием. Функция Game::getIntersection() возвращает пересеченное препятствие, когда препятствие появляется в области цилиндра.
  5. When the GameIntersection instance intersects with an obstacle, you can get its name using the getName() function or any other details using the corresponding functions.Когда экземпляр GameIntersection пересекается с препятствием, вы можете получить его имя, используя функцию getName(), или любые другие сведения, используя соответствующие функции.
Исходный код (C#)
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;

#region Math Variables
#if UNIGINE_DOUBLE
using Scalar = System.Double;
using Vec3 = Unigine.dvec3;
#else
using Scalar = System.Single;
using Vec3 = Unigine.vec3;
#endif
#endregion

[Component(PropertyGuid = "AUTOGENERATED_GUID")] // <-- this line is generated automatically for a new component
public class Intersections : Component
{

	// define an obstacle box and game intersection instance
	ObstacleBox obstacleBox;
	GameIntersection gi;

	// parameters of the virtual cylinder defining the volume
	// inside which to check for intersections
	float radius = 1.0f;		// radius of the cylinder
	vec3 p1 = new vec3(0, -3.0f, 3.0f);	// starting point of the ray
	vec3 p2 = new vec3(0, 3.0f, 3.0f);	// ending point of the ray

	private void Init()
	{

		// initialize the obstacle box and specify the name
		obstacleBox = new ObstacleBox(new vec3(1.0f));
		obstacleBox.Name = "main_obstacle";
		
		// initialize the game intersection object
		gi = new GameIntersection();

		// enable the visualizer
		Visualizer.Enabled = true;

	}

	private void Update()
	{

		// make the obstacle box move inside and outside the game intersection area
		Vec3 new_pos = new Vec3(0,0,2 + MathLib.Sin(Game.Time));
		obstacleBox.WorldPosition = new_pos;
		Visualizer.RenderPoint3D(new_pos, 0.15f, vec4.MAGENTA);

		// calculate the cylinder height (equals to the distance between the starting and ending points)
		Visualizer.RenderPoint3D(p1, 0.15f, vec4.BLUE);
		Visualizer.RenderPoint3D(p2, 0.15f, vec4.YELLOW);

		// create an instance of the GameIntersection class
		Obstacle obstacle = Game.GetIntersection(p1, p2, radius, 1, gi);

		//visualize the cylinder that represents the game intersection area
		Visualizer.RenderCylinder(radius, (p2-p1).Length, MathLib.SetTo(p1 + (p2 - p1) / 2, p2, vec3.UP, MathLib.AXIS.Z), vec4.WHITE);
		
		// check if the intersection of the cylinder with the obstacle has occurred
		if (obstacle != null)
		{
			obstacle.RenderVisualizer();
			Log.Message("The name of the obstacle is: {0} \n", obstacle.Name);
		}
	}

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