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;
}
}
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);