Search Unity

Setting position of moving multiple physics objects in code

Discussion in 'Scripting' started by AndreiTache, Dec 3, 2019.

  1. AndreiTache

    AndreiTache

    Joined:
    Nov 8, 2014
    Posts:
    31
    Hi everyone, sorry for the vague title; I don't know how else to describe it better..

    I'm making a boat game and I wanted to add some leaves that float in the water and the player could push around with the boat.

    Basically, I want the leaf to be pushed on the X/Z axis and have the Y position generated by a script. (based on the water wave's height)


    The way I have it now, I am spawning the leaves from a singular script (each with a sphere collider and a rigidbody with no gravity) then, from that same script (because I've read that it's faster than having individual scripts with Update functions for each leaf), I am setting their Y pos based on the wave's formula with rb.MovePosition().

    Thing is, the framerate takes a massive hit from constantly moving them up/down, and it seems to be caused by the movement itself, not anything else in the code.. If I remove everything and move all the leaves up by delta time, the game still lags. (even with no rigidbody, weirdly enough).
    If the rb's are active, but not moved via script, they don't lag at all...


    So, is there a more efficient way to move the objects, or a better way of doing this altogether?
    Thanks!
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    The motion probably triggers additional physics to be calculated.

    You could also achieve this by applying a force up/down depending on whether the leaf is below or above the water. This is also closer to what happens in reality.
     
  3. AndreiTache

    AndreiTache

    Joined:
    Nov 8, 2014
    Posts:
    31
    Hah, amazing! I've just reused the buoyancy script from the boat for each leaf (thinking it would chug to death) and the game is running more than 2x as fast :D Thanks for the help!

    It makes no sense to me that applying constant force is better than an absolute position, but here we are.. (and speaking of which, I thought rb.MovePosition was supposed to prevent the extra physics calculations..? or did I understand it wrong?)
     
  4. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    I think the reasoning is that a force is calculated in meters per second squared. A direct motion would take zero time, increasing the force to infinity. So for physics it's better to work with forces if possible.
     
    AndreiTache likes this.