Raycast and collision with entities without rigidbodies

I have a parallel job in which I’d like to detect which Entities I hit. Not all entities will have rigidbodies so the following isn’t so useful.

Entity e = physicsWorldSystem.PhysicsWorld.Bodies[hit.RigidBodyIndex].Entity

My job looks something like:

        [BurstCompile]
        struct ProjectilePhysicsRayJob : IJobForEach<Translation, Projectile>
        {
            public NativeArray<Unity.Physics.RaycastHit> raycastResultsInJob;
            [ReadOnly] public Unity.Physics.CollisionWorld collisionWorldInJob;
            public float deltaTime;

            public void Execute([ReadOnly] ref Translation position, ref Projectile projectile)
            {
                Unity.Physics.RaycastInput raycastInput = new Unity.Physics.RaycastInput
                {
                    Start = position.Value,                  
                    End = position.Value + (projectile.velocity * deltaTime),
                    Filter = Unity.Physics.CollisionFilter.Default
                };

                if (collisionWorldInJob.CastRay(raycastInput, out Unity.Physics.RaycastHit hit))
                {
                    raycastResultsInJob[projectile._tempIdx] = hit;
                }
            }
        }

How can I determine which Entities and/or meshes where hit?

Unity.Physics raycasts can only hit entities which have a PhysicsCollider component (a.k.a. becomes a rigid body). They include an index of that rigid body in the hit. The bodies stores the entity it was created from. So in your example just do:

Entity hitEntity = collisionWorldInJob.Bodies[hit.RigidBodyIndex].Entity;
1 Like

So, they do have a PhysicsCollider which gets added automatically from the Collider on the parent gameobject when ConvertGameObjectHierarchy(prefab.gameObject, conversionSettings) is called followed by Entity entity = entityManager.Instantiate(prefabEntity);

5265996--526956--upload_2019-12-10_19-37-9.png

If I create a cube in scene attach a ConvertToEntity and PhysicsShape (no rigidbody), Unity.Physics Raycast works fine. Just not when I instantiate in code.

This sounds similar to you issues in this post? Converting a prefab with collider then instantiating it at runtime with Unity.Physics
You don’t have a sample repro of the problem I could drop into the sample project do you?

I’ll try to build a repro. Been battling issues on multiple fronts with Unity.Physics and DOTS in general.