I have a GameObject which is supposed to be under-water, therefore its rigidbody has no gravity. The object is able to float up, down, left, and right (XY) on screen no problem. However, when this object collides with another object. It spins off into space indefinitely.
I have tried using Rigidbody.centerOfMass to control it’s center, but with no positive effect. (Does this even work if the rigidbody has no gravity?)
What would be the ideal solution for regaining the objects up-right position after a collision?
Set rigidbody.freezeRotation = true at Start: this will prevent rotational effects caused by physics in collisions - you still can rotate it with transform.Rotate or other transform related functions, but collisions will not make it rotate anymore.
Another alternative is to increase rigidbody.angularDrag to a higher value like 2 or 3: this will “break” the rotation quickly, but won’t self-right it.
If you still want to have some rotational effect and the self-right feature, set useGravity to true and apply a nulling force in FixedUpdate with AddForceAtPosition applied to a point near or above the object’s “head”:
var offset: float = 1; // offset from object's position (up direction)
function FixedUpdate(){
var point = transform.TransformPoint(offset * Vector3.up);
rigidbody.AddForceAtPosition(-Physics.gravity * rigidbody.mass, point);
}
This is actually correct behavior of the physics engine. An object in motion tends to stay in motion.
Because the object is underwater, water resists movement. A simple solution would be to add a FixedUpdate() function to your objects and call RigidBody’s AddForce() with a value calculated from the RigidBody’s velocity. Something like this might work for starters:
You might want to use a gameobject with a kinematic rigidbody (with no gravity applied to it) that you control via user input (or other scripting).
Then you make a joint (with a configurable joint) between your floating object (with a non-kinematic rigidbody) with some limits (restriction) on motion and rotation.
This way, you can still give a ‘floating’ behaviour (by making the y-motion free or slightly limited) to your object but its motion (and rotation) will be constrained with the kinematic rigidbody, so it will stay around.