Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on March 30, 2023, between 5 am & 1 pm EST, in the Performance Profiling Dev Blitz Day 2023 - Q&A forum and Discord where you can connect with our teams behind the Memory and CPU Profilers.
    Dismiss Notice

Question PhysicsCollider ray casting

Discussion in 'Physics for ECS' started by BigBite, May 31, 2020.

  1. BigBite


    Feb 20, 2013
    I have a particular collider I've been trying to raycast against. I'm getting zero results so far, nothing happens no matter what I do. My goal is to know if my mouse pointer is inside the collider. Trying to cast a ray from the mouse position to the center of the collider. Why doesn't this work?

    Code (CSharp):
    2. intersectPlane.Raycast(screenPointToRay, out var mouseHit);
    4. mouseWorldPos = screenPointToRay.GetPoint(mouseHit);
    6. Entities.WithoutBurst().ForEach(
    7. ((in PhysicsCollider collider, in BoxGrid grid, in Rotation rotation, in Translation translation)) =>
    8. {
    9. if (!collider.Value.Value.CastRay(ray, out var hit))
    10. {
    14.     //snap mouse to grid
    15.     Draw.WireBox(p,rotation.Value ,1);      
    16. }
    17. }).Run();
    CastRay always returns false. Entity has a PhysicsCollider and a PhysicsBody. I don't think it needs a physics body to be able to detect ray collisions, but I did try it with and with out one. The objects are also in a Sub Scene. Thanks in advance.
  2. MaxAbernethy


    Mar 16, 2019
    You'll need to transform the ray into collider space. The collider doesn't know about the entity's rotation and translation.

    I guess this will also be very slow if you have more than a few entities, so it would probably be better to use PhysicsWorld.CastRay(), which is accelerated by the broadphase. That way you don't need to iterate over entities or transform rays either.
  3. BigBite


    Feb 20, 2013
    Thanks I'll try to figure out how to transform the ray. I'm doing it this way in this case because I just want to know about a handful of entities (prolly like <10 tops). Tho I don't know if my case could still be faster if I use the PhysicsWorld to cast the ray, I imagine that would test all colliders by default.