Is it possible to Mathf.Clamp the position.x of Camera.main.screenToWorldPoint(Input.mousePosition)?

Im trying to make an Arkanoid-like game, using my mouse as the controller. How will I be able to apply Mathf.Clamp to my mouse if i’m using Camera.main.screenToWorldPoint(Input.mousePosition)?

so far i’ve made :

`public class Paddle : MonoBehaviour
[SerializeField] float mousePosInUnits;
[SerializeField] float minX = 1f;
[SerializeField] float maxX = 15f;
// Start is called before the first frame update
void Start()


// Update is called once per frame
void Update()
    mousePosInUnits = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
    Vector3 paddlePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    paddlePos.y = transform.position.y;
    paddlePos.z = transform.position.z;
    paddlePos.x = Mathf.Clamp(mousePosInUnits, minX, maxX);
    transform.position = paddlePos;


Yes, you can clamp the position, however the result is most likely not what you might expect. You’re just clamping the position, you do not confine the mouse in that space. So the mouse can still move outside of your defined area but the position will be clamped. It’s usually better to juse use a “virtual” mouse position and lock and hide the hardware mouse cursor. Now you can simply use the Mouse C axis which returns the current movement of the mouse in the x direction. Just scale it with your desired speed / sensitivity and add it to your position. That position can be clamped just fine.

Something like this:

void Update()
    if (Input.GetMouseButtonDown(0))
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    var p = transform.position;
    p.x += Input.GetAxis("Mouse X") * sensitivity;
    p.x = Mathf.Clamp(p.x, minX, maxX); 
    transform.position = p;

Note that the Mouse X axis is a delta value that is already frame based. Do not multiply it with Time.deltaTime. When you do the movement would become framerate dependent.

The mouse will be locked when the user presses the mouse down for the first time. You may also want to add something like:

    if (Input.GetKeyDown(KeyCode.Escape))
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;

to unlock the mouse when the user presses ESC.