Move GameObject to click position within a sprite
Hello,
I hope that you can help me.
I'm making a top down design game that is divided between 25 boxes, each of these boxes is separated by an image and with colliders. Each of these boxes has a number of sprites inside it, lets call them item. I want the user to be able to move these items to where ever the user clicks, I've put a button inside the item so the program know which one to move. The problem I have is that the item just moves to where the user clicks not staying within the square.
So far I have 3 ideas, maybe it help; 1. instead of moving to where the user clicks, move the item towards where the user clicked with physics, for example increasing the velocity, however I don't understand how to code this. 2. inside each square put a button of the same size inside, and only move to the click if the correct button is pressed. I'm trying this now however because my code is running on updating every from it just moves the item to where the button was pressed... I also understand this is a very messy way of doing it! 3. compare the world space coordinates of where the user clicked with the world coordinates of the square sprite and only apply the move if it's within the boundires. I could get the x and y limits of the sprite but I couldn't compare this with the world-space coordinates.. problems with comparing Vector3 with float.
Thanks in advance for any help!
My Code;
public class moveToMousePos : MonoBehaviour
{
public Camera myMainCam;
[SerializeField] Transform target;
Vector2 targetPos;
float speed = 10f;
private void Start()
{
targetPos = transform.position;
target = transform;
}
void Update()
{
//Like I said right now I'm trying to make this work with big buttons the size of the sqaure, this if statement checks if the button clicked = the square the item is in.
if (GameObject.Find("Main Camera").GetComponent<detectClickInside>().squarePressedString == GameObject.Find("Main Camera").GetComponent<Replace_square>().boxPressed.ToString())
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)myMainCam.ScreenToWorldPoint(Input.mousePosition);
target.position = targetPos;
}
if ((Vector2)transform.position != targetPos)
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
}
}
}
}
So in each of those boxes are a number of items with buttons inside I wish to move only within those boxes