- Home /
Underwater Swimming issues (Gravity and ConstantForce)
So I am trying to make some underwater swimming and I've had a lot of issues. I've managed to fix some and work around others, but three things still eludes me.
The most important one is swimming up and down. I found a tutorial online that used ConstantForce to move the player up and down. There are a few issues with this though. When I dive (move downwards) I pass through the terrain, which I normally don't when I walk around normally. The code I use for this movement is the following c# code which runs in my Update method:
if(isUnderWater && Input.GetButton("Jump"))
constantForce.relativeForce = new Vector3( 0, 200, 0);
else if(isUnderWater && Input.GetButton("Crouch"))
constantForce.relativeForce = new Vector3( 0, -200, 0);
else
constantForce.relativeForce = new Vector3( 0, 0, 0);
Is there a better way to do this, or a solution to my collision issue? This method feels rather unnatural because gravity for some reason is ignored after I press the jump (or crouch) button once, even though the gravity value in the Character Motor is above zero.
If required (I don't think so though) here's the changes that are made when I go into the water:
private void SetUnderWater()
{
// render new fog with blue color
RenderSettings.fog = true;
RenderSettings.fogColor = new Color(0, 0.4f, 0.7f, 0.6f);
RenderSettings.fogDensity = 0.08f;
RenderSettings.fogStartDistance = 0.0f;
foreach(Transform child in transform)
if(child.gameObject.tag == "MainCamera")
child.camera.backgroundColor = new Color(0, 0.4f, 0.7f, 1);
light.intensity = 0f;
chMotor.movement.gravity = 2;
chMotor.movement.maxFallSpeed = 3;
chMotor.movement.maxForwardSpeed = 3;
chMotor.movement.maxSidewaysSpeed = 3;
chMotor.movement.maxBackwardsSpeed = 3;
chMotor.jumping.enabled = false;
isUnderWater = true;
}
So to sum it up:
How do I avoid diving through my terrain, or should I use a different approach to swimming?
If I stick to this method, how would I get the gravity to work (Or something else that adds some realism to the underwater movement)?
Thanks a lot for reading.