Unity DOTS中的物理系统即Unity.Physics,这里使用一个简单的demo(小球弹起效果),来说明一下 碰撞 Trigger。
1、创建sphere(注意,要去掉ShpereCollider),添加Physics Shape,ShapeType 选择 Sphere,PhysicsShape 选择RaiseTriggerEvents;添加 Physics Body。(当然添加ConvertToEntity是必须的,关于ConvertToEntity的使用可以看一下官网demo)
2、创建plane(注意,要去掉MeshCollider),添加Physics Shape,ShapeType 选择 Plane。
3、小球弹起,触发逻辑
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Unity.Physics;
using Unity.Collections;
using Unity.Physics.Systems;
public class PhysicalSystem : SystemBase
{
private BuildPhysicsWorld m_buildPhysicsWorld;
private StepPhysicsWorld m_stepPhysicsWorld;
protected override void OnCreate()
{
m_buildPhysicsWorld = World.GetOrCreateSystem<BuildPhysicsWorld>();
m_stepPhysicsWorld = World.GetOrCreateSystem<StepPhysicsWorld>();
}
protected override void OnUpdate()
{
TriggerJob triggerJob = new TriggerJob()
{
PhysicVelocityGroup = GetComponentDataFromEntity<PhysicsVelocity>()
};
Dependency = triggerJob.Schedule(m_stepPhysicsWorld.Simulation, ref m_buildPhysicsWorld.PhysicsWorld, Dependency);
}
}
public struct TriggerJob : ITriggerEventsJob
{
public ComponentDataFromEntity<PhysicsVelocity> PhysicVelocityGroup;
public void Execute(TriggerEvent triggerEvent)
{
if (PhysicVelocityGroup.HasComponent(triggerEvent.EntityA))
{
Debug.Log("EntityA is sphere = " + triggerEvent.EntityA);
var velocity = PhysicVelocityGroup[triggerEvent.EntityA];
velocity.Linear.y = 10f;
PhysicVelocityGroup[triggerEvent.EntityA] = velocity;
}
if (PhysicVelocityGroup.HasComponent(triggerEvent.EntityB))
{
Debug.Log("EntityB is sphere = " + triggerEvent.EntityB);
var velocity = PhysicVelocityGroup[triggerEvent.EntityB];
velocity.Linear.y = 10f;
PhysicVelocityGroup[triggerEvent.EntityB] = velocity;
}
}
}
|