Search Unity

Is ray/spherecasting too expensive for character controllers?

Discussion in 'Scripting' started by Sendatsu_Yoshimitsu, Oct 21, 2018.

  1. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    I'm working on making my own character controller for the first time, and one of my big stumbling blocks is figuring out how to run collision detection in a performant fashion. Right now, each character performs one downwards raycast each frame to check the slope, a spherecast to detect any potential conflicts with geometry, and if worse comes to worse and the character somehow ends up clipping into something solid, it recursively casts one ray per clipping collider to generate pushback.

    This looks and feels 100% fine when I run it on a single capsule guy in a greyboxed level, but my understanding is that casting is expensive enough that you generally don't want to be doing it on a per-frame basis; is there a better approach I'm neglecting that'll make this scale better when I want 20-30 characters moving around at once, or is regular casting the cost of doing business when it comes to producing highly adaptable controllers with solid gamefeel?
     
  2. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    AshwinMods likes this.
  3. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    Hmm, thanks.. and yeah, they aren't slow slow, but they're slow enough that I'm really leery about building them into the base of a low-level component that's gonna end up on dozens of objects per level. The profiler looks okay for now, and I know thinking beyond that is the sort of premature optimization they explicitly tell you not to worry about, but I have sufficiently little understanding of unity's physics API that paranoia makes me comfortable. :)

    Out of curiosity, if you don't use casting how do you run collision checks on your controller?
     
  4. hippocoder

    hippocoder

    Digital Ape

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    I do an overlap check then use https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html to get me the sensor normals and depth, and after that it's all maths. It's instead of lots of raycasts. I only do this because of accuracy, I didn't care abput perf either way. When it comes to character controllers your biggest nemesis is probably getting it working right.
     
    AmazingRuss likes this.
  5. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    Oh that's neat, I never thought of doing it that way... either way you're right about performance not being that big of a problem, but I'll probably end up playing with a few alternatives either way; thank you for the feedback! :)