Igor
Igor

Reputation: 64

How limit the transform position in Unity?

I'm looking to way to limit the transform position in Y axis of my object. To moving I'm using that code

transform.position += Vector3.down * Time.deltaTime * speed;

Object is moving only when player is holding the button, after that the object is going back to 1st position. How can I block the moving for example from 6 to -6 in Y axis?

Upvotes: 1

Views: 9648

Answers (2)

derHugo
derHugo

Reputation: 90872

As I understand the question you want the object being limited to stay between -6 and 6.

You can e.g. use Mathf.Clamp to limit position.y like

transform.position = new Vector3(transform.position.x,      
                                 Mathf.Clamp(transform.position.y + Time.deltaTime * speed, -6.0f, 6.0f), 
                                 transform.position.z);

In contrary to the other answer this limits the movement exactly to the given values and prevents any overshooting. It also would still allow to move the object back once one limit is reached while the other answer ignores any future movement once a limit is reached.

Upvotes: 1

Johnny
Johnny

Reputation: 9529

Since transform.position and Vector3.down * Time.deltaTime * speed both have (x, y, z) as they are Vector3 you could simply check the Y component and skip the movement between the specified range, e.g.

if(transform.position.y < -6 || transform.position.y > 6)
{
    // the Vector3.down is (0, -1, 0) so this operation will change only Y component anyway
    transform.position += Vector3.down * Time.deltaTime * speed;
}

In the original OP overshoot has not been mentioned but as @derHugo pointed out you could limit move to avoid overshoot. One possibility is like this, it will limit the move regarding the nearest border, preventing also to jump from one border to another...

private static float OutsideLimitedMove(float current, float move, float bottomLimit, float topLimit)
{
    //----->---------|  not allowed  |---------<-----
    // fromBottom   -6               6       fromUp 

    if(current >= -6 && current <= 6) 
        return 0f;

    float predictedY = current + move;

    //fromBottom
    if(current < bottomLimit && predictedY > bottomLimit) 
        return Math.Min(bottomLimit - current, move);

    //fromUp
    if (current > topLimit && predictedY < topLimit)
        return Math.Max(topLimit - current, move);

    return move;
}

Vector3 predictedMove = Vector3.down * Time.deltaTime * speed;
float y = OutsideLimitedMove(transform.position.y, predictedMove.y, -6, 6);
transform.position += new Vector3(predictedMove.x, y, predictedMove.z);

Upvotes: 3

Related Questions