About 'Limit With Mathf.Clamp()'!

In this video (objectives)…

  1. Figure out the range we want to allow the paddle to move on x axis.
  2. use Mathf.Clamp() to limit the paddle's movement.

After watching (learning outcomes)… Use Mathf.Clamp() to limit the movement of a game object.

(Unique Video Reference: 9_BR_CUD)

We would love to know…

  • What you found good about this lecture?
  • What we could do better?

Remember that you can reply to this topic, or create a new topic. The easiest way to create a new topic is to follow the link in Resources. That way the topic will…

  • Be in the correct forum (for the course).
  • Be in the right sub-forum (for the section)
  • Have the correct lecture tag.

Enjoy your stay in our thriving community!

1 Like

Not sure if there is a scenario where we would want to set different limits for min and max, but otherwise we only need one variable here which is half the width of the paddle. Then we can limit movement as follows

    [SerializeField]
    float screenWidthInUnits = 16f;

    [SerializeField]
    float paddleHalfWidth = 1f;

    // Update is called once per frame
    void Update()
    {
        transform.position = new Vector2(
            Mathf.Clamp(Input.mousePosition.x / Screen.width * screenWidthInUnits,
                        paddleHalfWidth,
                        screenWidthInUnits - paddleHalfWidth),
            transform.position.y);
    }
1 Like

Hi Anton,

I made my code to get the width of the paddle. So, if you change the paddle width, it gets it Programmatly.

public class Paddle : MonoBehaviour
{
    [SerializeField] float screenWidthInUnits = 16f;
    PolygonCollider2D collider;
    float minX;
    float maxX;

    // Start is called before the first frame update
    void Start()
    {
        collider = (PolygonCollider2D)gameObject.GetComponent(typeof(PolygonCollider2D));
        minX = collider.bounds.size.x / 2;
        maxX = collider.bounds.size.x / 2;
    }

    // Update is called once per frame
    void Update()
    {
        float mousePosInUnit = (Input.mousePosition.x / Screen.width * screenWidthInUnits);
        Vector2 paddlePos = new Vector2(transform.position.x, transform.position.y);
        paddlePos.x = Mathf.Clamp(mousePosInUnit, 0 + minX, screenWidthInUnits - maxX);
        transform.position = paddlePos;
    }
}
1 Like

Very nice Carlos.

Although that 0 + is bothering me a bit. :wink:

Nice I might have to steal that code from you :innocent:

Can we also use mathf.clamp to limit the balls movement?

Privacy & Terms