PhysicsWorldSingleton CastRay not hitting collider

Hi all, just another frustrating Friday night trying to figure out how dots works. Does anyone have insight on what might be going wrong with my ray raycast? Don’t mind me caching Camera.main.

I’ve tried versions of the code below using SystemBase and ISystem, with and without the attributes, using just the PhysicsWorldSingleton and the CollisionWorld, having Unity convert the BoxCollider into the components and using Physics Shape component, using CollisionFilters.Default and doing new Filter with ~0n binary whatevers. No matter what I do I can’t get it to hit anything. I’ve also swapped the cube out with a 3d Plane, and other shapes.

Running the latest version of everything on pre-release 6. It’d be pretty cool if this is a bug because if it isn’t I’m and I’ve waisted 6 hours doing something obviously wrong I’m going to delete my project and go back to programming in Monobehaviour land.

Last note, this is a netcode for entities project, w/ a server world and client world, can’t imagine this would be an issue, unless the server requires all raycasts be done on the server, at this point nothing would suprise me.

Thanks guys,

using UnityEngine;
using Unity.Entities;
using Unity.Physics;
using Unity.Mathematics;
using Unity.Physics.Systems;

namespace EntityPrototypes.RTSPrototype
{
    [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))]
    [UpdateBefore(typeof(PhysicsSystemGroup))]
    public partial struct TestRaycastSystem : ISystem
    {
        float3 _rayStart;
        float3 _rayEnd;

        public void OnCreate(ref SystemState state)
        {
            _rayStart = float3.zero;
            _rayEnd = float3.zero;
        }

        public void OnUpdate(ref SystemState state)
        {
            var camera = Camera.main;
            var physicsWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>().CollisionWorld;

            Debug.DrawRay(_rayStart, _rayEnd, Color.green);

            if (Input.GetKeyDown(KeyCode.Mouse0))
            {
                Debug.Log("Mouse Button Pressed");

                var ray = camera.ScreenPointToRay(Input.mousePosition);

                _rayStart = ray.origin;
                _rayEnd = ray.origin + ray.direction * 200f;

                Debug.Log($"Ray Start: {_rayStart}, Ray End: {_rayEnd}");

                var raycastInput = new RaycastInput()
                {
                    Start = _rayStart,
                    End = _rayEnd,
                    Filter = CollisionFilter.Default,
                };

                var hit = physicsWorld.CastRay(raycastInput, out var raycastHit);
            
                if (hit)
                {
                    UnityEngine.Debug.Log($"Hit Ground at position: {raycastHit.Position}");
                }

            }
        }
    }
}
1 Like

Not sure how to set this to resolved.

I figured out the issue, it was due to it being a netcode for entities project.

Got this error when setting up a secondary test project, never got it in the first one:
[ClientWorld] The default physics world contains 2 dynamic physics objects which are not ghosts. This is not supported! In order to have client-only physics, you must setup a custom physics world:

  • Entity(344:1) Sphere
  • Entity(345:1) Ground
    UnityEngine.Debug:LogError (object)

Note, you can set the objects as Static and this error goes away, but the raycast still fails.

Adding the Ghost Authoring Component shows the following error.
9828465--1413267--upload_2024-5-11_8-29-20.png

I added the Ghost Authoring Component, converted the Ground object into a prefab, which stopped it from showing up into the scene. I’m guessing all ghost components need to be instantiated from code?

Then I setup a ground authoring scrip with the prefab attached, and then a system to instantiate it. Setup an InputEvent for the button click, and then it all started working.

I feel like I’m missing something. I’ve watched netcode for entities tutorials where they had a ground being raycasted to that wasn’t a ghost and it worked fine. If anyone has input on this that would be awesome.

1 Like

Another follow-up. This is apparently an already know bug, but I don’t see it reported or documented anywhere other than the thread below, the workaround as described worked for me. The other video tutorials I’ve looked at already have ghosts in one form or another already in the scene so it was never an issue.

Question - Troubles with raycasting, netcode and client-only worlds - Unity Forum

By adding a 3D cube to the entity scene, adding a Physics Body set to Kinematic, Ghost Authoring Component set to Predicted & Dynamic, and a Net Code Physics Config component with lag compensation turned on, client-side ray casts work as expected.

2 Likes

-_- i stumbled on this same issue

What fixed it for me was adding ‘RigidBody’ to the object

Apparently (hope to be wrong) the Physics World can interact with objects that have a RigidBody, so when you try to do any Physics Cast or related queries, it does not know how to match objects that have just ‘colliders’. SO you need to attach a rigidbody to it and then it gives it a 'rigidbodyIndex" with which it can calculate simple things like physics raycasts

Maybe somebody has another though? Thanks OP

When you say “RigidBody”, do you mean the Rigidbody authoring component?
Just having a collider authoring component (any Collider such as Sphere, Box etc. or a PhysicsShape component from the custom authoring) works here, but I am unsure of the implications with Netcode, specifically on the client side.
This part was discussed in the other posts, from @Anhysbys , above.

What do you mean by “rigidbodyIndex”? Do you mean the PhysicsWorldIndex Entities component? If yes, this one is automatically added when creating pure colliders or rigid bodies using authoring components, but needs to be added if creating rigid body Entities for Unity Physics at runtime, as shown in this tutorial.

For sample scenes for both pure Unity Physics use cases and Unity Physics with Netcode use cases, please have a look at the official PhysicsSamples and NetcodeSamples projects respectively.

@Anhysbys : I am sorry for answering here only now, and I am glad you figured out your problem. For the future, for issues regarding physics and Netcode, it’s always better to ask in the Netcode forum first.

1 Like

Yes, Rigidbody authoring component (the UnityEngine.RigidBody component found in the normal unity setup without having DOTS, that gets Baked)

with “rigidodyIndex” i mean

            Unity.Physics.RaycastHit hit;
            hit.Entity;
            hit.RigidBodyIndex; <===

I assume that if a RigidBodyIndex is not found => not mapped to a valid RaycastHit?

I think it has something to do with how the baking happens, maybe something is added to check “If you baked something with a rigid body, make sure these physics systems are registered” and thus runs a system for the PhysicsWorld and correlates the RigidBodyIndex

If you start a new project with a full copy of the Physics / NetcodeSamples → things work! Yey, but as soon as you want to remove some the samples or start from scratch - things get a bit weird since they are intertwined. And you need to be aware “For this system to work, it needs “this”, “this” and “this””
That’s kind of how i got into this error - i wanted to make a Very simple Collider, add it to the scene and test it. Server side worked, client side - no
Once i added Rigidbody and set to Kinematic → it worked also on client side

I have a netcode scene with a single ghosted unit on it and I also spawn the same ghosted units on the go. If I remove the preset unit, raycasts won’t work for spawned units. I’m new to ECS and not sure if this is a bug or if I have to somehow bake the ghosted unit into the physics system myself.

@Bromm : I suggest you repost this question in a new thread with the Netcode-for-Entities label.