Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to Raycast properly (rigidbody character controller)

Discussion in 'Physics for ECS' started by RecursiveEclipse, Mar 15, 2020.

  1. RecursiveEclipse

    RecursiveEclipse

    Joined:
    Sep 6, 2018
    Posts:
    298
    I'm making a character controller and am trying to get a ground check to work but I can't seem to get the rays pointed in the right direction for CollisionWorld.CastRay. I have a capsule on a plane with a pole at origin, the capsule is offset on the Z axis a bit. This is what I have as ground check:

    Code (CSharp):
    1.  
    2. bool IsGrounded(AABB renderBounds) {
    3.     var rayTarget = renderBounds.Center + (-math.up() * (renderBounds.Extents.y + .0001f));
    4.  
    5.     var rayInput = new RaycastInput {
    6.         Start = renderBounds.Center,
    7.         End = rayTarget,
    8.         Filter = new CollisionFilter {
    9.             BelongsTo = 1u,
    10.             CollidesWith = ~1u,
    11.             GroupIndex = 0
    12.         }
    13.     };
    14.     return CollisionWorld.CastRay(rayInput);
    15. }
    When I try this I can keep jumping when I shouldn't be, and checking what is being hit by the cast shows the pole entity. I copied the rayTarget = ... code to a monobehavour and drew a line using gizmos and that shows as it should, a line from the center of my capsule to the bottom. So I tried what was said here: https://forum.unity.com/threads/cant-get-raycasts-to-work-solved.674818/, and subtracted renderBounds.Center from rayTarget but the ray still points to origin. This is probably something dumb on my part, but I don't know what is wrong.

    AABB renderBounds is WorldRenderBounds of my capsule.
     
  2. Rory_Havok

    Rory_Havok

    Joined:
    Jun 25, 2018
    Posts:
    70
    Your code looks correct. One thing to check is if your character capsule has a collider then your ray starting inside that will always hit that, with a fraction of zero. So you'll need to filter out the capsule. (I'm guessing maybe the it hit the pole sometimes with zero fraction while you were testing, but when its not hitting the pole it will be hitting the capsule.)
     
  3. RecursiveEclipse

    RecursiveEclipse

    Joined:
    Sep 6, 2018
    Posts:
    298
    Thanks. The capsule does have a collider. Which bit would I need to mask if I have the capsule marked as the first available custom slot in the physics layers? What's weird is I can get it to jump only once when the pole isn't there, so that implies that the Ray would end directly at origin.

    Also what is a fraction in this context?