Unity 3D – odd behaviour with rigid bodies

If you’ve ever done much coding using “physics” engines, then you’ll have seen the hilarity that ensues when you accidentally try to make two object occupy the same or even part of the same space. The objects in question will be subjected to literally massive forces, flinging both the objects far and wide.

My initial thought was just to set the velocity of the rigid body to zero, I’d experimented directly with the rigid body velocity to implement a kind of variable friction, and it worked well. However this time I used the Vector3 Set method, rather than just assigning a Vector3 to the field (no idea why…)

myRigidbody.velocity = aNewVelocity



Using Set actually has no effect, so there are obviously different mechanisms going on here, it looks like the get and set is actually doing more than just changing the velocities value… I did have a look in the c# reference code but the only real clue you get is:

extern public Vector3 velocity { get; set; }

It seems that just setting the value alone is not enough, and while I know that in an ideal world you should only be adding forces to a rigid body, but in this case where teleportation causes large forces you don’t really have much option.

Oh if you do need to teleport objects it’s well worth checking there isn’t another object very close to your destination, and immediately after zero the velocity.

      // find a spot not too near and not too far...
      Vector3 pos = new Vector3(0,0,0);
      while(pos.magnitude < 20) {
        pos.Set(Random.Range(-40, 40), 1.0f, Random.Range(-40, 40));
        // getNearest returns null is there is no targetable objects in tractor range...
        if (getNearest(pos)) pos.Set(0,0,0); // don't let them be too close to each other

      rb.position = pos;
      rb.velocity = new Vector3(0,0,0);

While its nice that Unity has released the c# code, I somehow can’t see them releasing the native code too… which is a shame as open sourcing Unity wouldn’t stop their licencing income, and support plans would also still be generating income, they’d also get a small army of people submitting big fixes and improvements, but I guess those business types just ain’t brave enough to take a win, win situation !

Anyhow after just a few days of coding I ended up with this running on my phone… (not bad for a beginner)

Leave a comment

Your email address will not be published. Required fields are marked *