Home > Back-end >  Mathf.Clamp inside of a sphere radius Unity
Mathf.Clamp inside of a sphere radius Unity

Time:12-28

I have a simple joystick move script. I restricted its movement on x and z axis with a Mathf.Clamp. What I am trying to achive is to use that function inside a sphere radius.

I need the gameobject movement restrict its movement if the gameobjects position is outside of the radius.

   void UpdateMoveJoystick()
    {
        horizontale = moveJoystick.Horizontal;
        float ver = moveJoystick.Vertical;
        Vector2 convertedXY = ConvertWithCamera(Camera.main.transform.position, horizontale, ver);
        Vector3 direction = new Vector3(convertedXY.x, 0, convertedXY.y).normalized;
        transform.Translate(direction * 0.02f * speed, Space.World);
        Quaternion targetRotation = Quaternion.LookRotation(direction);

       RestrictMovement();
    }

     void RestrictMovement()
    {
        var position1 = transformPos.transform.position.x;
        var position2 = transformPos.transform.position.x;
        var position3 = transformPos.transform.position.z;
        var position4 = transformPos.transform.position.z;
        float xMovementClamp = Mathf.Clamp(transform.position.x, position1  = leftBoundry, position2  = rightBoundry);        
        float zMovementClamp = Mathf.Clamp(transform.position.z, position3  = DownBoundry, position4  = UpBoundry);
        transform.position = new Vector3(xMovementClamp, transform.position.y, zMovementClamp);
    }

Anyway Thanks for help :)

CodePudding user response:

The function you are looking for is Vector2.ClampMagnitude. This method takes a Vector2 and allows you to ensure that the magnitude (or vector length) is no longer than the desired length (or the radius of the circle).

With this in mind, the RestrictMovement method from your code would look something like this:

public float boundryRadius = 20.0f;

void RestrictMovement()
{
    var positionXY = new Vector2(transform.position.x, transform.position.y);

    positionXY = Vector2.ClampMagnitude(positionXY, boundryRadius);

    transform.position = new Vector3(positionXY.x, positionXY.y, transform.position.z);
}

This would clamp the GameObject in the boundryRadius specified around the world position of 0, 0, 0. Additional maths can be used to change the centre of the circular boundary.

  • Related