Search Unity

Trying to optimize my 2D character; rigidbody settings

Discussion in 'Physics' started by Marscaleb, Sep 3, 2019.

  1. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,037
    I've been reading some of the details about how rigidbodies work so I could optimize my game; cull out unnecessary calculations in my game's code.

    I'm not using the default physics; I'm calculating the character's movement through custom code. With that in mind, I suspect I should be setting my rigidbody to be kinematic. The documentation says that way I don't need to worry about things like in-engine gravity and other forces, which is great because I'm calculating my own gravity.
    But the documentation also says "A Kinematic Rigidbody 2D does not collide with other Kinematic Rigidbody 2Ds or with Static Rigidbody 2D." But I do want to use the engine's collision; if I write my own collision code it's just going to take me extra time and it won't run as fast anyway.
    The way the documentation describes it, it sounds like I couldn't have two characters in my game collide with each other just because I'm making my own gravity calculation. But yet it seems to really be even worse, because when I test using a kinematic character in my game, they fall right through the world geometry. My world geometry doesn't have any rigidbody components, so the kinematic objects actually don't collide with ANY collision. (I guess except for the dynamic rigidbodies.)

    So first of all, are there some basic settings I'm missing? Should I be able to have a kinematic actor collide with a generic collider with no rigidbody if I just tweak the right settings?

    And second to that, what would be the best options change for my situation? Since my regular characters are using custom movement code, what can I do to remove the physics calculations I don't need (like gravity) without removing the calculations I DO need (like collision)?
     
  2. JanOtt

    JanOtt

    Joined:
    Apr 23, 2019
    Posts:
    183
    Hi Marscaleb!

    If you want to make use of the engine's physics calculations while still using custom movement code (and gravity), you need to use a dynamic rigidbody, disable it's gravity (in the inspector) and move it by setting its velocity directly.

    So essentially, you'd calculate your character's velocity yourself in code, then override the rigidbody's velocity every FixedUpdate() like this:

    rigidbody.velocity = [your own calculated velocity vector];


    That's how I've done it in the past and it works like a charm!