I am trying to build a 2d strategy game where you can build on a grid based world and all buildings will have different sizes like 3x3, 2x3 and they will be builded on the grid, based on their sizes. Without making them snap to grid depending on their size, i can make them just follow the mouse and build wherever i want but i need to make them snap to grid depending on their size. How can i achieve this ? Alternate image link : Map hosted at ImgBB — ImgBB
[EDIT] : Here is the final code down below. Right now i can snap and follow the selected building based on the mouse’s position with sending a ray and checking the building grids but still this action does not depend on the building’s sizes. Here is a video of current situation.
BuildingScript
[SerializeField]
private MousePositionChecker mousePositionChecker;
private Transform currentBuilding;
private bool hasPlaced;
// Update is called once per frame
void LateUpdate () {
if (currentBuilding != null && !hasPlaced)
{
//Vector3 m = Input.mousePosition;
//Vector3 p = Camera.main.ScreenToWorldPoint(m);
//currentBuilding.position = new Vector3(p.x, p.y, 0);
if(mousePositionChecker.mousePos)
currentBuilding.position = mousePositionChecker.mousePos.position;
if (Input.GetMouseButtonUp(0))
{
hasPlaced = true;
}
}
}
public void SetItem(GameObject b)
{
hasPlaced = false;
currentBuilding = ((GameObject)Instantiate(b)).transform;
}
MousePositionScript
public Transform mousePos;
// Update is called once per frame
void Update () {
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
if (hit != null && hit.collider != null && hit.transform.tag=="BuildArea")
{
mousePos = hit.transform;
}
}
