Limit Value of the position X (Help)

Hi, I would like to create a script that would limit the range of values ​​of the position Y.
The object is a buoyancy boat. What I want is to limit the position “Y”, that it does not exceed a number.

When you reach that maximun “Y” position , the script do something to raise no more, and so that when the ship reaches a minimum height can not go down more.

What I want is a limiting value of the “Y”, because i don’t want the boat flying and sinking…

Thanks a lot

you’d do something like

// Update or FixedUpdate
void Update() { 
    Vector3 currentPosition = transform.position;
    float clampedY = 
       Mathf.Clamp( currentPosition.y, minY, maxY);

    if( ! Mathf.Approximate( clampedY, currentPosition.y ) ) 
    { 
        currentPosition.y = clampedY; 
        transform.position = currentPosition; 
    }
}

that modifys position only if the transform.position.y is above maxY or below minY. you can remove that Mathf.Approximate if you want to be exact, but its good to modify stuff as little as you need if your using rigidbody.

2 Likes

I can’t understand the code i try to put it but i get a lot of errors…
thanks for the help

1 Like

heres the code again but a little simplified, you’ll need to specify minY and maxY to what you want the minimum and maximum y values to be.

public float minY = 0.0f, maxY = 10.0f;// we want to keep the y between 0 and 10
// Update or FixedUpdate
void Update() { 
    // get the position to a variable
    Vector3 currentPosition = transform.position;
    // modify the variable to keep y within minY to maxY
    currentPosition.y = 
       Mathf.Clamp( currentPosition.y, minY, maxY);
    // and now set the transform position to our modified vector
    transform.position = currentPosition;
}
4 Likes

Thank you, that was very helpful