Well here I am for yet another exciting post on Unity3D. Today I’ll be telling you how to restrict the player’s movement in a particular range. I’ll be doing it here for the X-Axis and Y- Axis. You can do the same for Z-axis too. Its not that difficult. I’ll assume that you have at least some basic knowledge of Unity Scripting. For more detailed information, you can refer to the Unity3D scripting references. Before beginning, Unity is all about a 3D Vector, since the objects are represented as 3D vectors in real space. Here, Vector3 Comes into play.

 ball;
void Start(){
        ball = GameObject.("Ball");   //Find the game object in the scene whose tag is "Ball".
}

// If Player's X exceeds minX or maxX..

if (ball.transform.position.x <=minX || ball.transform.position.x >=maxX)
{
    // Create values between this range (minX to maxX) and store in xPos
    float xPos = Mathf.Clamp(ball.transform.position.x, minX   0.1f, maxX);

    // Assigns these values to the Transform.position component of the Player
    ball.transform.position = new Vector3(xPos, ball.transform.position.y,0);
}

// If Player's Y exceeds minY or maxY..
if (ball.transform.position.y <= minY || ball.transform.position.y >=maxY)
{
    // Create values between this range (minY to maxY) and store in yPos
    float yPos = Mathf.Clamp(ball.transform.position.y, minY, maxY);

    // Assigns these values to the Transform.position component of the Player
    ball.transform.position = new Vector3(ball.transform.position.x, yPos,0);
}

So this is how it works. I’ve attached the links with the code. So that it works fine and If you’re having any problems with it, you can just click on the highlights. Cheers.

 

Post By- Siddharth Verma