To Restrict The Player’s Movement In An Axis In Unity3D

May 7, 2013 | Rishabh Agrawal | General

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


THE AUTHORRishabh Agrawal

Rishabh Agrawal is the founder of Creatiosoft, a company focused on creating high-quality software for the iGaming industry, specialising in poker and card games. With years of experience, Rishabh is dedicated to delivering engaging and user-friendly gaming experiences. Through this blog, he shares his passion and insights to help readers understand the latest trends and advancements in iGaming.

Recent Posts

The Future of Mobile Gaming: What to Expect in the Next 5 Years

Over the years, mobile gaming has seen amazing development and innovation utilized by the game development company in India. It…
06 Jun 2023 Rishabh Agrawal

How Do I Get Started With NFT Gaming?

The popularity of the NFT game has created a different fan base. There was a time when games were a…
18 Jul 2022 Rishabh Agrawal

What Are The Top Trends in NFT Marketplace 2022?

The NFTs are the new engaging and revolutionary technology across the globe. Though, these non-fungible tokens appeared for the first…
09 Jun 2022 Rishabh Agrawal