- Home /
Making an object float in water
var gravity=Vector3.zero;
var target_gravity=Vector3(0,-10,0);
var water_level=65f;
function Update(){
var surface_distance=water_level-transform.position.y;
target_gravity=Vector3(0,-10,0); //you are above water, do normal gravity
if(surface_distance>0) target_gravity=Vector3(0,10,0); //you are underwater, reverse target gravity
gravity=Vector3.Lerp(gravity,target_gravity,2 * Time.deltaTime);
rigidbody.MovePosition(transform.position + (gravity * Time.deltaTime));
}
I have made this simple water floating script by just reversing gravity when a person goes above or below the water surface, and it works, except that when the object finally starts to settle down near the surface (stops bobbing up and down so much) it just sort of jitters there. Because gravity is switching between +/- small amounts.
My question is what would you do to this code to make the bobbing of the object more realistic when it finally starts to settle on the surface? I'm stumped so far
Answer by Kiwasi · Jan 19, 2015 at 05:03 AM
What I do for water physics is use the colliders bonding box to figure out what percentage is underwater. Then I add a force upwards based on that percentage.
Have a look at Pond Wars (linked in my profile) to see the effect in action.
That seems like a good system but if I'm not mistaken that would still suffer from "jitters" as the object begins to settle down on the water's surface, unless a dampening mechanism is added.
Is there any sort of way I can fix this jitter problem starting with the code I already use?
Your answer
Follow this Question
Related Questions
Object buoyancy in water on different water levels? 1 Answer
Having trouble with player boat movement with buoyancy pack 0 Answers
Bouyancy Effector Issues 0 Answers
Pro Water - Matching Rotation 0 Answers
Bouyancy timing issue 0 Answers