- Home /
Help me With clamping gameobjects Codes inside.
Hello Masters. I have Lets say 10 Sprites on the scene. I move them with drag and drop. But i want each sprites Clamp and not go beyond for specific point. i move them with this code. (found Here again). private float startPosX; private float startPosY; private bool isBeingHeld = false; private Vector3 mousePos;
#region Drag And Drop Codes
private void Update()
{
if (isBeingHeld == true)
{
GetMousePos();
gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, 0);
}
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
GetMousePos();
startPosX = mousePos.x - transform.localPosition.x;
startPosY = mousePos.y - transform.localPosition.y;
isBeingHeld = true;
}
}
void GetMousePos()
{
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
}
private void OnMouseUp()
{
isBeingHeld = false;
}
#endregion
Comment
Best Answer
Answer by mrmatt1877 · Feb 28, 2021 at 04:25 PM
you want to clamp the x and y positions before adding them to the new Vector2
if (isBeingHeld == true)
{
GetMousePos();
float xPos = Mathf.Clamp(mousePos.x - startPosX, xMin, xMax);
float yPos = Mathf.Clamp(mousePos.y - startPosY, yMin, yMax);
gameObject.transform.localPosition = new Vector3(xPos , yPos , 0);
}
Your answer
Follow this Question
Related Questions
Problems with finding the clicked sprite 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to get pivot of sprite in script 2 Answers