碰撞接触处理
Sometimes you may need to implement your own contact handler for colliding physical bodies. In this example, you will learn how to visualize contact points, display debug information, and add a hit effect (sparks) at the point of impact. 有时候您可能需要实现您自己的接触处理程序来碰撞物理物体。在本例中,您将学习如何可视化接触点、显示调试信息以及在撞击点添加撞击效果(火花)。
Preparing the content准备内容#
To create sparks, we are going to use the VFX add-on (you can download it on https://store.unigine.com).要创建火花,我们将使用 VFX附加组件(您可以在 https://store.unigine.com 网站上下载)。
Create a new project in UNIGINE SDK Browser and import the VFX add-on to it.在UNIGINE SDK浏览器中创建一个新项目并导入VFX插件。
When you open the project in the UnigineEditor, you will see the default scene containing some dynamic objects. Let's create another box and get some information about the contacts it will have with other objects.当您在UnigineEditor中打开项目时,您会看到包含一些动态对象的默认场景。让我们创建另一个框,并获取关于它与其他对象的接触的一些信息。
Making the Objects Collidable使物体可碰撞#
The box is a dynamic object, so to be able to collide it needs a body and a collision shape. Add a Rigid body and a shape via the Physics tab of the Parameters window.盒子是一个动态对象,所以为了能够碰撞,它需要一个主体和一个碰撞形状。通过Parameters窗口的Physics选项卡添加一个Rigid body和一个形状。
Enabling High Priority Contacts启用高优先级接触#
On collision, contacts are distributed randomly between the interacting bodies to optimize performance: some are handled by the first body, others by the second. For a body, contacts that it handles itself are internal (access to them is fast), and contacts handled by other bodies are external.在碰撞时,接触在相互作用的物体之间随机分布以优化性能:一些物体由第一个物体处理,另一些由第二个物体处理。对于一个体来说,它自己处理的接触是 internal(访问它们是快速的),其他体处理的接触是external。
The box is a high-priority body for us and we want to track its collisions with maximum efficiency. We can make the box handle most of its contacts itself (so that most of them are internal). To do so, select the box and check High Priority Contacts in the Physics tab (or do it via code).该盒子对我们来说是一个高优先级的物体,我们希望以最大的效率跟踪它的碰撞。 我们可以让盒子自己处理大部分触点(这样大多数触点都是内部的)。 为此,请选中该框并选中Physics选项卡中的High Priority Contacts(或通过代码执行此操作)。
Creating a Hit Effect Node创建命中效果节点#
We will use a Particle System to create a node that simulates sparks.我们将使用粒子系统来创建一个模拟火花的节点。
-
In the UnigineEditor, click Create -> Particle System -> Particles. Place the object somewhere in the world, rename it to sparks, and adjust its parameters:在UnigineEditor中,单击Create -> Particle System -> Particles。将对象放置在世界的某个地方,将其重命名为sparks,并调整其参数:
- Number Per Spawn = 10
- Radius = 0.02
- Life Time = 0.2
- Period = inf
- Duration = 0
- In the Surface Material section, assign library_spark1.mat material (it is located in the data -> vfx -> materials -> library_vfx folder of your project).在Surface Material部分中,分配library_spark1.mat材料(它位于项目的data -> vfx -> materials -> library_vfx文件夹中)。
- Switch to the data folder in the Asset Browser. Right-click the sparks node and select Create a Node Reference. A sparks.node file will be generated in the data folder.在资源浏览器中切换到data文件夹。右键单击sparks节点并选择Create a Node Reference。将在data文件夹中生成一个sparks.node文件。
- Delete the sparks object from the scene, we no longer need it since it will be loaded via code.从场景中删除sparks对象,我们不再需要它,因为它将通过代码加载。
Algorithm Description算法描述#
The algorithm we are going to use can be described as follows:我们将要使用的算法可以描述如下:
- We create three variables (lastContactTime, lastContactPoint, lastContactInfo) to keep the time and position of the last occurred contact and some info about it.我们创建了三个变量(lastContactTime, lastContactPoint, lastContactInfo)来保存最后一次发生接触的时间和位置以及有关它的一些信息。
- We subscribe for an event to perform some actions when each contact emerges. The handler function (OnContactEnter()) takes the body and the index of the contact.我们订阅一个事件,以便在每个接触出现时执行一些操作。处理程序函数(OnContactEnter())接受接触的主体和索引。
- If the contact is internal, we save its time and position.如果接触是内部的,我们保存了它的时间和位置。
-
We get both physical bodies participating in this contact (body0, body1). We check if our box has hit another physical object.我们让两个实体都参与到这个接触中(body0, body1)。我们检查盒子是否碰到了另一个物体。
- If any of body0 and body1 exists (and it is not the body of our box), then we have found this object. We get details about this body and render it in the viewport using Visualizer.如果body0和body1中的任何一个存在(并且它不是盒子的主体),那么我们就找到了这个对象。我们获取这个主体的详细信息,并使用 Visualizer在视口中呈现它。
- Otherwise, the box has hit some static object (a surface with the Collision option enabled). We make this surface highlighted in the viewport as well.否则,盒子会撞上某个静态对象(启用了Collision选项的表面)。我们也在视口中突出显示这个表面。
- We add details we are interested in (e.g., the contact impulse).我们添加我们感兴趣的细节(例如,接触脉冲)。
- We spawn a hit effect if the impulse is strong enough. Physics event handlers are called in the main thread, so it is safe to create nodes inside the OnContactEnter() function.如果冲动足够强烈,我们就会产生命中效果。物理事件处理程序在主线程中调用,因此在OnContactEnter()函数中创建节点是安全的。
- Finally, in the Update() method we display the info and create a slow motion effect for one second.最后,在Update()方法中,我们显示信息并创建一秒钟的慢动作效果。
Component Code组件代码#
Create a new C# component, call it ContactsHandler, and open it in your IDE.创建一个新的c#组件,命名为ContactsHandler,并在IDE中打开它。
[Component(PropertyGuid = "YOUR_COMPONENT_GUID")]
[Component(PropertyGuid = "YOUR_COMPONENT_GUID")]
Copy the source code below and save it to the ContactsHandler.cs file.复制下面的源代码并将其保存到ContactsHandler.cs文件中。
ContactsHandler.cs
using System;
using System.Collections;
using System.Collections.Generic;
using Unigine;
#region Math Variables
#if UNIGINE_DOUBLE
using Vec3 = Unigine.dvec3;
#else
using Vec3 = Unigine.vec3;
#endif
#endregion
// DO NOT CHANGE THE PropertyGuid VALUE
[Component (PropertyGuid = "YOUR_GUID")]
public class ContactsHandler : Component
{
// For debugging
public bool debug = true;
// A node that will be loaded on contact (a hit effect in our case)
public AssetLinkNode contactEffect;
// Time, position and some info of the last occurred contact
private DateTime lastContactTime;
private Vec3 lastContactPoint;
private string lastContactInfo;
private void Init()
{
Body body = node.ObjectBody;
if (body)
{
// For debug purposes, we can render certain contacts depending on their type
body.EventContacts.Connect((b) => b.RenderInternalContacts());
// A handler to be fired when each contact emerges
body.EventContactEnter.Connect(OnContactEnter);
}
}
// This function takes the body and the index of the contact
private void OnContactEnter(Body body, int num)
{
// Enable Visualizer to see the rendered contact points
Visualizer.Enabled = true;
if(body.IsContactInternal(num))
{
if (debug)
{
// The time of the contact
lastContactTime = DateTime.Now;
// The position of the contact
lastContactPoint = body.GetContactPoint(num);
// We get both physical bodies participating in this contact
Body body0 = body.GetContactBody0(num);
Body body1 = body.GetContactBody1(num);
Body touchedBody = null;
// We check if our object has hit another physical object.
// If any of the bodies exists and it's not the body of our object
// then we have found another physics-driven object that hit it
if (body0 && body0 != body) touchedBody = body0;
if (body1 && body1 != body) touchedBody = body1;
if (touchedBody)
{
// Our object has touched a physics-driven object.
// We save the info about the body
lastContactInfo = $"body {touchedBody.Name} of {touchedBody.Object.Name}";
// Render it in the viewport
Visualizer.RenderObject(touchedBody.Object, vec4.BLUE, 0.5f);
}
else
{
// It has touched a surface with Collision enabled
lastContactInfo = $"surface #{body.GetContactSurface(num)} of {body.GetContactObject(num).Name}";
// Highlighting the surface
Visualizer.RenderObjectSurface(body.GetContactObject(num), body.GetContactSurface(num), vec4.BLUE, 0.5f);
}
// You can add details you are interested in (e.g., the contact impulse)
lastContactInfo += $"\nimpulse: {body.GetContactImpulse(num):0.0}";
}
// We spawn a hit effect if the impulse is strong enough
if (body.GetContactImpulse(num) > 0.3f && !contactEffect.IsNull)
{
contactEffect.Load(body.GetContactPoint(num), MathLib.RotationFromDir(body.GetContactNormal(num) * MathLib.RotateY(90)));
}
}
}
private void Update()
{
// Here we display the info and create a slow motion effect for one second
if (debug)
{
if((DateTime.Now - lastContactTime).Seconds < 1.0f)
{
// Slow motion effect
Game.Scale = 0.4f;
Visualizer.RenderMessage3D(lastContactPoint, vec3.ONE, $"last contact: \n{lastContactInfo}", vec4.GREEN, 2, 24);
}
else
{
// All the other time the speed will be normal
Game.Scale = 1.0f;
}
}
}
}
Applying Logic to the Object将逻辑应用于对象#
Switch to the UnigineEditor and assign the ContactsHandler component to the box node.切换到UnigineEditor并将分配给 ContactsHandler组件给box节点。
Specify the sparks.node in the Contact Effect field.在Contact Effect字段中指定sparks.node。
Adjust the position/rotation of the first_person_controller node to get a better initial view of the scene.调整first_person_controller节点的位置/旋转,以获得更好的场景初始视图。
Click Run to see the result. As the box is rolling around, the physics-driven objects and collidable surfaces it hits along the way are highlighted, and contact details are displayed near the contact point. Whenever a collision occurs, it triggers an asset spawning and a slow motion effect.单击Run查看结果。当盒子滚动时,物理驱动的物体和它一路上碰到的可碰撞表面会高亮显示,接触点附近会显示接触细节。每当发生碰撞时,它就会触发资源刷出和慢动作效果。
To disable the debug information, uncheck the Debug box under Node Components And Properties.要禁用调试信息,取消选中Node Components And Properties的Debug选项。
This is how you can easily track collisions and run necessary logic on time: spawn particles, play sounds, and destroy fracture objects.这就是您如何轻松跟踪碰撞并及时运行必要的逻辑:生成粒子,播放声音,并破坏断裂对象。