# Difficulty with mouse movement (Solved)

Greetings. I’m having trouble when configuring the motion of a 2D object with the mouse. I need the object to be confined in the walls and that has only movement on the y axis when dragging with the mouse clicked. In the script below I am unable to confine the object and movements are on the x axis as well.
I am not able to adjust the script. I appreciate the help.

``````#pragma strict

var moveSpeed : float = 0.1;
var mousePosition : Vector2;
var springSpeed : SpringJoint2D;
var velFrequency : float;

function Start()
{

}

function Update()
{
if (Input.GetMouseButton(0))
{
springSpeed.frequency = 0;
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
}

if(Input.GetMouseButtonUp(0))
{
springSpeed.frequency = velFrequency;
}

}
``````

Try this

``````transform.position = Vector2.Lerp(transform.position, Vector2(transform.position.x, mousePosition.y), moveSpeed);
``````
1 Like

This should lock the X-axis:

``````        springSpeed.frequency = 0;
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
mousePosition.x = transform.position;
transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
``````
1 Like

OK but:

``````mousePosition.x = transform.position.x;
``````

Thank you.

And how can I restrict the object inside the box? It crosses the box when moving to the extremities.

This will give you a way to set the bounds for movement:

``````// These are the x & y bounds
var xMin : float;
var xMax : float;
var yMin : float;
var yMax : float;

// Clamp the new x-position based on transform.position.x between xMin and xMax
var xPos : float = Mathf.Clamp(transform.position.x, xMin, xMax);

// Clamp the new y-position based on mousePosition.y between yMin and yMax
var yPos : float = Mathf.Clamp(mousePosition.y, yMin, yMax);

// Lerp to new position that is clamped between bounds
transform.position = Vector2.Lerp(transform.position, Vector2(xPos, yPos), moveSpeed);
``````
1 Like

Thank you. I will test and I report.

That’S Perfect! Solved the problem. Thank you so much for your help.

1 Like