- Home /
How to implement ECS trigger collisions? (Unity.Physics 0.50)
How could I set a simple ECS collision detection in Unity DOTS, on trigger.
I haven't seen any decent documentation about it and I haven't found any tutorials with Entities 0.50
. I have Raise Trigger Events
selected in Physics Shape
, but from there I don't know what to add / implement it in SystemBase
?
Comment
Answer by andrew-lukasik · May 09 at 11:54 AM
I haven't seen any decent documentation about it and I haven't found any tutorials with ECS 0.50
It's all here: https://github.com/Unity-Technologies/EntityComponentSystemSamples
I suggest downloading the whole repo as there are quite a few interesting samples in there.
TriggerWarningAuthoring.cs:
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Physics;
using Unity.Physics.Systems;
using UnityEngine;
public class TriggerWarningAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
[SerializeField] string _message = "How dare you!";
void IConvertGameObjectToEntity.Convert ( Entity e , EntityManager dst , GameObjectConversionSystem cs )
{
if( !enabled ) return;
dst.AddComponentData( e , new TriggerWarning{
Message = _message
} );
}
}
public struct TriggerWarning : IComponentData
{
public FixedString4096Bytes Message;
}
[Unity.Burst.BurstCompile]
struct TriggerWarningJob : ITriggerEventsJob
{
[ReadOnly] public ComponentDataFromEntity<TriggerWarning> TriggerWarningData;
public void Execute ( TriggerEvent evt )
{
Entity A = evt.EntityA;
Entity B = evt.EntityB;
if( TriggerWarningData.HasComponent(A) )
Debug.Log($"a message: {TriggerWarningData[A].Message}");
if( TriggerWarningData.HasComponent(B) );
Debug.Log($"a message: {TriggerWarningData[B].Message}");
}
}
[UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
[UpdateAfter(typeof(ExportPhysicsWorld))]
[UpdateBefore(typeof(EndFramePhysicsSystem))]
public partial class TwitterSimulationSystem : SystemBase
{
StepPhysicsWorld _stepPhysicsWorldSystem;
protected override void OnCreate ()
{
_stepPhysicsWorldSystem = World.GetOrCreateSystem<StepPhysicsWorld>();
RequireForUpdate( GetEntityQuery( new EntityQueryDesc{
All = new ComponentType[]{ typeof(TriggerWarning) }
} ) );
}
protected override void OnStartRunning()
{
base.OnStartRunning();
this.RegisterPhysicsRuntimeSystemReadOnly();
}
protected override void OnUpdate ()
{
var job = new TriggerWarningJob
{
TriggerWarningData = GetComponentDataFromEntity<TriggerWarning>( isReadOnly:true ) ,
};
Dependency = job.Schedule( _stepPhysicsWorldSystem.Simulation , Dependency );
}
}