This feature handles building placement in a grid-based system, checks if the position is buildable, and
detects potential collisions with existing objects.
Check Buildable Area Code
public bool IsPositionBuildable(Vector2 position)
{
RaycastHit2D hit = Physics2D.Raycast(position, Vector2.zero, Mathf.Infinity, buildableArea);
if (hit.collider != null)
{
return true; // Position is within the buildable area.
}
Debug.Log("collider hit");
return false; // Position is outside the buildable area.
}
This function checks if a given position is within a buildable area using a raycast.
Mouse Position and Building Placement Code
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); // Get mouse position
mousePosition.z = 0f;
closestTile = gridTilemap.WorldToCell(mousePosition); // Get closest tile based on mouse position
Vector3 closesTilePos = gridTilemap.GetCellCenterWorld(closestTile); // Get center of the tile
if (Input.GetMouseButtonDown(0) && building == true)
{
Debug.Log("it clicks");
buildable = GameObject.Find("BuildableArea").GetComponent().IsPositionBuildable(mousePosition);
bool noCollision = GetComponent().CheckForCollision(closesTilePos);
Debug.Log(noCollision);
if (buildable && GameManager.selection && noCollision)
{
if (GameManager.manPwr - GameManager.selectedUnit.GetComponent().price < 0)
{
Debug.Log("Not enough resources");
building = false;
return;
}
else
{
GameManager.manPwr -= GameManager.selectedUnit.GetComponent().price;
Instantiate(GameManager.selectedUnit, new Vector3(closesTilePos.x, closesTilePos.y, -1), Quaternion.identity);
building = false;
}
}
}
else if (Input.GetMouseButtonDown(0) && removing == true)
{
Collider2D[] collisions = Physics2D.OverlapBoxAll(new Vector3(closesTilePos.x, closesTilePos.y, -1), new Vector2(1,1), 0);
if (collisions.Length > 0)
{
foreach (Collider2D collider in collisions)
{
Destroy(collider.gameObject);
}
return;
}
return;
}
This code tracks the mouse position for building placement, ensuring it is buildable and collision-free
before placement. It also supports removing objects with a mouse click.
Collision Check Code
public bool CheckForCollision(Vector2 position)
{
colliderSize = GameManager.selectedUnit.GetComponent().size; // Get the size of the current unit's collider
Collider2D[] colliders = Physics2D.OverlapBoxAll(position, colliderSize, 0, collisionLayer);
if(colliders.Length > 0)
{
foreach (Collider2D collider in colliders)
{
Debug.Log("Collision detected with: " + collider.gameObject.name);
// Handle the collision here.
}
return false;
}
return true;
}
This function checks for collisions using an OverlapBox and logs any detected collisions, returning `true`
if no collision is found.