# 十字路口 (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:主要有三种类型的交叉口:

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.ShapeObject类有自己的getIntersection()函数。这些函数用于检测物体的特定形状或特定表面的交点。

## 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.通过使用不同重载的WorldgetIntersection()函数，您可以找到与指定的包围体边界相交的对象和节点，或识别对象与不可见跟踪线的第一个交集。

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: 1 if the intersection was found; otherwise, 0. Intersected nodes can be found in the vector that passed as an argument to the function.这些函数返回值指示交叉搜索的结果:1 如果十字路口被发现;否则, 0 。交叉节点可以在向量作为参数传递给函数。

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.在下面的示例中,发动机检查路口边界框,显示了控制台分割的对象的名称。

``````#include "AppWorldLogic.h"
#include <UnigineObjects.h>
#include <UnigineEditor.h>

#include <UnigineVisualizer.h>

using namespace Unigine;
using namespace Math;

int AppWorldLogic::update()
{

// initialize a bounding box and vector for intersected nodes
WorldBoundBox boundBox(Vec3(0.0f), Vec3(1.0f));
Visualizer::renderBoundBox(boundBox, Mat4_identity, vec4_blue);

Vector<NodePtr> nodes;

// check the intersection with nodes
int result = World::getIntersection(boundBox, nodes);
if (result)
{
for (int i = 0; i < nodes.size(); i++)
{
Log::message("Intersected node: %s \n", nodes.get(i)->getName());
}
Log::message("The number of intersected nodes is: %i \n", nodes.size());
}

return 1;
}``````

As the sun has limitless bounds, if present in the scene, it always intersects with the initialized bounding box.因为太阳有无限的边界，如果出现在场景中，它总是与初始化的边界框相交。

### 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: 1 if the intersection was found; otherwise, 0. 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 vector that passed as an argument to the function.这些函数返回指示交集搜索结果的值:如果找到交集，则返回1;否则,0。您可以通过相交线的起始点(vec3 p0)和结束点(vec3 p1)或通过(BoundBox, BoundFrustum, BoundSphere)分别获得对象与直线或边界体的交点。交叉节点可以在作为参数传递给函数的向量中找到。

For WorldBoundFrustum, there are two modes of getting intersections:对于WorldBoundFrustum，有两种获取交叉口的模式:

#### Finding Objects Intersected by a Bounding Box查找对象分割的边界框#

In the example below, the engine checks intersections with a bounding box and shows the names of intersected objects in the console.在下面的例子中，引擎用一个边界框检查交叉，并在控制台中显示交叉对象的名称。

In the update() method, the engine checks the intersection and shows the message about intersection.update()方法中，引擎检查交叉口并显示有关交叉口的消息。

``````#include "AppWorldLogic.h"
#include <UnigineObjects.h>
#include <UnigineEditor.h>

#include <UnigineVisualizer.h>

using namespace Unigine;
using namespace Math;

int AppWorldLogic::update()
{

// initialize a bounding box and vector for intersected objects
WorldBoundBox boundBox(Vec3(0.0f), Vec3(1.0f));
Visualizer::renderBoundBox(boundBox, Mat4_identity, vec4_blue);

Vector<ObjectPtr> objects;

int result = World::getIntersection(boundBox, objects);
if (result)
{
for (int i = 0; i < objects.size(); i++)
{
Log::message("Intersected object: %s \n", objects.get(i)->getName());
}
Log::message("The number of intersected objects is: %i \n", objects.size());
}

return 1;
}``````

#### Finding Objects Intersected by a Bounding 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秒。

``````#include "AppWorldLogic.h"
#include <UnigineObjects.h>
#include <UnigineEditor.h>

#include <UnigineVisualizer.h>

#include <UnigineApp.h>
#include <UnigineInput.h>
#include <UnigineGame.h>

using namespace Unigine;
using namespace Math;

int AppWorldLogic::init()
{
Visualizer::setEnabled(true);

return 1;
}

int AppWorldLogic::update()
{

if (App::clearKeyState(Input::KEY_SPACE))
{
// get a reference to the camera
PlayerPtr player = Game::getPlayer();
CameraPtr camera = player->getCamera();

mat4 projection = camera->getAspectCorrectedProjection(float(App::getHeight()) / float(App::getWidth()));

// bound frustrum for the intersection and a list to store intersected objects
WorldBoundFrustum bf(projection, camera->getModelview());
Visualizer::renderFrustum(projection, camera->getIModelview(), vec4_blue, 20.0f);

Vector<ObjectPtr> objects;

// perform the intersection search with the bound frustrum
World::getIntersection(bf, objects);

// draw the bound spheres of all objects' surfaces found by the search
for (int i = 0; i < objects.size(); i++)
{
BoundSphere bs = objects[i]->getBoundSphere();
Visualizer::renderBoundSphere(bs, objects[i]->getWorldTransform(), vec4_red, 20.0f);
}
}

return 1;
}``````

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():要仅搜索与在渲染 能见距离内且 LODs 可见的对象的交点，请使用以下命令 方法而不是 getIntersection()

``World::getVisibleIntersection(player->getWorldPosition(), 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 intersectionWorldIntersection类实例。通过使用这个类，您可以得到交点(坐标)、对象的相交三角形的索引和相交曲面的索引。
• 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 texcoordWorldIntersectionTexCoord类实例。通过使用这个类，你只能得到交点的纹理坐标。

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.在下面的例子中，引擎用光线追踪线检查路口，并在控制台中显示消息。

``````#include "AppWorldLogic.h"
#include <UnigineObjects.h>
#include <UnigineEditor.h>

using namespace Unigine;
using namespace Math;

int AppWorldLogic::update()
{

WorldIntersectionPtr wi = WorldIntersection::create();
ObjectPtr o;

if (wi)
o = World::getIntersection(Vec3(0.0f), Vec3(1.0f), 1, wi);

if (o)
{
Log::message("Intersected object is: %s \n", o->getName());
}
return 1;

}``````

## 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.物理交集功能检测与物理形状或断裂体的交集。如果对象没有实体，这个函数检测对象与启用了Physics Intersection标志的表面(多边形)的交集。当您需要找到与对象形状的交集(而不是多边形)时，Physics类的交集函数是获得它的最佳方法。

The picture above shows how the getIntersection() function detects the shape that intersects with the line上面的图片展示了getIntersection()函数检测形状线相交的

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.使用Player::getDirectionFromScreen()函数定义并初始化两个点(p0和p1)。
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 getShape(), getPoint() functions.当追踪的对象相交线,所有的表面分割对象的改变他们的材料参数。如果对象有一个形状,其信息将显示在控制台。PhysicsIntersection类实例得到交点的坐标和Shape类对象。你可以得到所有这些字段使用getShape(), getPoint()功能。

``````#include "AppWorldLogic.h"
#include <UnigineObjects.h>
#include <UnigineEditor.h>
#include <UnigineApp.h>
#include <UnigineGame.h>
#include <UniginePhysics.h>

using namespace Unigine;
using namespace Math;

int AppWorldLogic::init()
{
// create a Mesh instance with a box surface
MeshPtr mesh = Mesh::create();

// create a new dynamic mesh from the Mesh instance
ObjectMeshDynamicPtr dynamic_mesh = ObjectMeshDynamic::create(mesh);

dynamic_mesh->setWorldTransform(translate(Vec3(0.0f, 0.0f, 2.0f)));

// assign a body and a shape to the dynamic mesh
BodyRigidPtr body = BodyRigid::create(dynamic_mesh);
ShapeBoxPtr shape = ShapeBox::create(body, vec3(0.2f));

return 1;
}

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

int AppWorldLogic::update()
{
// initialize points of the mouse direction
Vec3 p0, p1;

// get the current player (camera)
PlayerPtr player = Game::getPlayer();
if (player.get() == NULL)
return 0;
// get width and height of the current application window
int width = App::getWidth();
int height = App::getHeight();
// get the current X and Y coordinates of the mouse pointer
int mouse_x = App::getMouseX();
int mouse_y = App::getMouseY();
// get the mouse direction from the player's position (p0) to the mouse cursor pointer (p1)
player->getDirectionFromScreen(p0, p1, mouse_x, mouse_y, width, height);

// create the instance of the PhysicsIntersection object to save the information about the intersection
PhysicsIntersectionPtr intersection = PhysicsIntersection::create();
// get an intersection
ObjectPtr object = Physics::getIntersection(p0, p1, 1, intersection);

// if the intersection has occurred, change the parameter of the object's material
if (object)
{
for (int i = 0; i < object->getNumSurfaces(); i++)
{
object->setMaterialParameterFloat4("albedo_color", vec4(1.0f, 1.0f, 0.0f, 1.0f), i);
}

// if the intersected object has a shape, show the information about the intersection
ShapePtr shape = intersection->getShape();
if (shape)
{
Log::message("physics intersection info: point: (%f %f %f) shape: %s\n", intersection->getPoint().x, intersection->getPoint().y, intersection->getPoint().z, shape->getTypeName());
}
}

return 1;
}``````

## Game Intersection游戏的十字路口#

The GetIntersection() functions of the Game class are used to check the intersection with obstacles (pathfinding nodes):Game类的GetIntersection()函数用于检查有障碍物的交叉口(寻径节点):

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.Define两个点(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()函数获得它的名称，或者使用相应的函数获得任何其他细节。

``````#include "AppWorldLogic.h"
#include <UnigineObjects.h>
#include <UnigineEditor.h>

#include <UniginePathFinding.h>
#include <UnigineGame.h>
#include <UnigineApp.h>

using namespace Unigine;
using namespace Math;

int AppWorldLogic::init()
{
Visualizer::setEnabled(true);

// create an obstacle
obstacle_box = ObstacleBox::create(vec3(1.0f));
obstacle_box->setName("main_obstacle");

return 1;
}

int AppWorldLogic::update()
{

// make the obstacle box move inside and outside the game intersection area
Vec3 new_pos = Vec3(0, 0, 2 + Math::sin(Game::getTime()));
obstacle_box->setWorldPosition(new_pos);
Visualizer::renderPoint3D(new_pos, 0.15f, vec4(1, 0, 1, 1));

// calculate the cylinder height (equals to the distance between the start and end points)
Visualizer::renderPoint3D(p1, 0.15f, vec4(0, 0, 1, 1));
Visualizer::renderPoint3D(p2, 0.15f, vec4(0, 1, 1, 1));

// create an instance of the GameIntersection class
GameIntersectionPtr intersection = GameIntersection::create();
ObstaclePtr obstacle = Game::getIntersection(p1, p2, radius, 1, intersection);

//visualize the cylinder that represents the game intersection area
Visualizer::renderCylinder(radius, (p2 - p1).length(), setTo(p1 + (p2 - p1) / 2, p2, vec3_up, AXIS_Z), vec4(1, 1, 1, 1));

// check if the intersection of the cylinder with the obstacle has occurred
if (obstacle)
{
obstacle->renderVisualizer();
Log::message("The name of the obstacle is: (%s)\n", obstacle->getName());

}
return 1;

}``````