Why wont this script let me get back on shore?

#pragma strict
var waterLevel : float;
var groundLevel : float;
private var isUnderwater : boolean;
private var canSwim : boolean = false;
private var underGround : boolean = false;
private var chMotor : CharacterMotor;
function Start () {
chMotor = gameObject.GetComponent(CharacterMotor);
}

function Update ()
{
if((transform.position.y < waterLevel) != isUnderwater) {
isUnderwater = transform.position.y < waterLevel;
if(isUnderwater) SetUnderwater ();
if(!isUnderwater) SetNormal ();
}
if(transform.position.y < groundLevel)
{
canSwim = true;
underGround = true;
}

else
{
underGround = false;
}

if(isUnderwater && Input.GetKey(KeyCode.E))
{
GetComponent.().relativeForce = Vector3(0,-200, 0);
}
else
{
GetComponent.().relativeForce = Vector3(0, 0, 0);
}

if(isUnderwater && Input.GetKey(KeyCode.Q))
{
GetComponent.().relativeForce = Vector3(0, 200, 0);
}
}
function SetNormal () {
chMotor.movement.gravity = 20;
chMotor.movement.maxFallSpeed = 20;
chMotor.movement.maxForwardSpeed = 6;
chMotor.movement.maxSidewaysSpeed = 6;
canSwim = false;
}
function SetUnderwater () {
chMotor.movement.maxFallSpeed = 5;
chMotor.movement.maxForwardSpeed = 4;
chMotor.movement.maxSidewaysSpeed = 4;
}

this script runs and lets the character swim. But once I try to get back on shore it will not let me it will keep me in the water any help would be nice. Thank you.

This isn’t the right place to post scripting questions. This is the forum for posting about Unity’s documentation (the manual & scripting reference). For answers to specific problems you’re having with unity or your own code, you would be better posting to answers.unity3d.com

But while I’m here it looks like the first ‘if’ in your update function that checks for entering & exiting the water has some logic problems. Try changing it to something like this:

    if (isUnderwater)
    {
        // currently underwater. Check for exiting water:
        if (transform.position.y > waterLevel)
        {
            SetNormal();
        }
    } else {
        // currently on land. Check for entering water:
        if (transform.position.y < waterLevel)
        {
            SetUnderwater();
        }
    }
1 Like

alright I didn’t know that thanks for the response I will test it