So I’ve a bit of an interesting problem with isometric tilemaps in Unity.
I have a two dimensional array of gameobjects. The position of the objects in this array determines where their associated sprites are rendered on an isometric tilemap.
I can then currently click on a position on the tilemap and get an associated gameobject in two ways.
Use
var worldPos = Camera.main.ScreenToWorldPoint(Input.MousePosition);
var tilePos = sampleTilemap.WorldToCell(worldPos);
To get the tile/cell position, then use that position to get the object from the array.
Give the object a Collider2d in world space and use
var worldPos = Camera.main.ScreenToWorldPoint(Input.MousePosition);
var hit = Physics2D.OverlapPoint(worldPos);
to get the collider that has reference to the associated gameobject.
But the question now comes is what to do if I want to mouse select an area to get multiple objects at once?
First solution is to give every gameObject an associated Collider2D shape and then use
var hits = Physics2D.OverlapArea(startPos, endPos);
But as the scene has over 10,000 trees that’s a lot of colliders to instantiate on scene load and should I be worried about memory usage?
Secondly I could get the tile/cell positions that lie under the selection area using the following and some algebra.
if (Input.GetMouseButtonDown(0))
{
_startPos = InputController.MousePosition;
}
if (Input.GetMouseButton(0))
{
_endPos = InputController.MousePosition;
var startWorldPos = Camera.main.ScreenToWorldPoint(_startPos);
var endWorldPos = Camera.main.ScreenToWorldPoint(_endPos);
//get corner tiles
//algebra to get all included tiles in selection area
To get the below image.
But is that a lot of work to be doing during one update frame?
If anyone has a more elegant solution or more widely used solution I would gladly appreciate it.