Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question PhysicsCollider ray casting

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

  1. BigBite

    BigBite

    Joined:
    Feb 20, 2013
    Posts:
    108
    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):
    1.  
    2. intersectPlane.Raycast(screenPointToRay, out var mouseHit);
    3.  
    4. mouseWorldPos = screenPointToRay.GetPoint(mouseHit);
    5.  
    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. {
    11.    
    12.    
    13.    
    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

    MaxAbernethy

    Joined:
    Mar 16, 2019
    Posts:
    53
    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

    BigBite

    Joined:
    Feb 20, 2013
    Posts:
    108
    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.