- Home /
floating on water physics
In this 2D platform game im using the character platform controller to move around my character. I made this box of water and when u get in u should be able to swin in, sink, and float and move on the surface unless when i press down i ca swin underwater again.
i already have most of it done, my main problems are when im on the surface, i have 2 colliders for the water, one in general and another just for the surface, my 3 problems are, i cant jump when floating, cant go underwater either, the floating system is far from what im looking for.
just showing some example of wat im using to make the character float on water and jump, im using the 'MoveTowards' function to force the player to float on the surface but as u cant see its using all axes instead of only the y axes because i dunno how to fix that
function OnTriggerStay (hit : Collider)
{
if(hit.gameObject.tag == "WaterSurface")
{
WaterSurfaceTouch = true;
movement.gravity = 0;
movement.maxFallSpeed = 0;
if (WaterSurfaceTouch == true)
{
gameObject.transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
if(Input.GetButtonDown ("Jump"))
{
myNewVelocity = Vector3(0,26,0);
setVelocity.SetVelocity(myNewVelocity);
}
}
}
any kind of tip would be nice
Answer by aldonaletto · Apr 26, 2012 at 02:29 AM
It seems this code would push the player towards the center of the trigger. If you want to just push it to the water height, use Mathf.MoveTowards instead:
if (WaterSurfaceTouch == true){ transform.position.y = Mathf.MoveTowards(transform.position.y, target.position.y, speed * Time.deltaTime); }This will move the player only vertically to the same target y coordinate (whatever target is).
oh, i was using Vector3 and $$anonymous$$athf at the same time... right thx that fix that part; and forgot to mention using that code for some reason doesnt work as well as it should; because as u can see i've set the maxFallSpeed and gravity to 0, but i still dont remain on the surface most of the time, i either sink or move upwards, wats the cause of this?
I was thinking its because the character has some inertia thats why i set the movement.velocity = Vector3(0,0,0); OnTriggerEnter
[EDIT]ok nvm, change lots of things and the overall system a little, works 99% right.... edit again, scratch that, works 100% :)
Answer by pudd1nG · Apr 26, 2012 at 02:42 AM
I would suggest adding force based on how submerged the object is. However because you're using a CharacterController not a rigidbody you will need to apply the .Move() function instead of .AddForce().
Without writing this for you, take the depth (height) of the water, get the distance between the bottom of the character and the bottom of the water (probably via raycast) and apply an upward movement based on the distance. It will take a little tuning to get it to look right but is the nicest way outside of rigidbody controllers to achieve a bobbing in water effect.