- Home /
Other
Compare Position of two gameobjects and if true, do nothing, help me please!
Hey everybody! I'm trying to create a tiled-based ingame-building system and I need to check if two tiles have the same position and if so you cant put another tile on this position, but I have trouble with my logic, here is what I've tried:
if (Input.GetMouseButtonDown(1)) // if player use tool
{
if (AreaNear(whiteRect.transform.position, tempGameobj.transform.position, 0.2f)) // tile is on tile
{
Debug.Log("Test");
}
else if(HotbarInventory.Instance.equipmentSlot[HotbarInventory.Instance.i].GetComponent<Image>().sprite.name == "hoe_wood" && !AreaNear(whiteRect.transform.position, tempGameobj.transform.position, 0.1f))
{ // if player holds correct tool & tile is not on tile
Instantiate(preFab).transform.position = whiteRect.transform.position;
}
}
//Check distance between two Gameobject
public bool AreaNear(Vector3 obj1, Vector3 obj2, float minDistance = 0)
{
return ((obj1.x < obj2.x + minDistance && obj1.x > obj2.x - minDistance) && (obj1.y < obj2.y + minDistance && obj1.y > obj2.y - minDistance) && (obj1.z < obj2.z + minDistance && obj1.z > obj2.z - minDistance));
}
//tile (acre) is tagged with buildable
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "buildable")
{
tempGameobj = other.gameObject;
}
}
When I place my tile by clicking mouseButton(1) and click again to place another one on top of it - it works correct - nothing happens. When I place tile and move my player and then try to place a tile at the same position it places one on top of it? Hope someone can help me, here is a also a picture:
Answer by text23d · Nov 30, 2017 at 04:53 PM
Hm, why don't you make an array (kind of table) with x,y coordinates for each of "square"/tile? then if you mouse over the object (use Raycast hit), you can know coordinates of gameobject by just knowing gameobject.transform.position. to compare the two, you can make two Vector3 vars (for example, Vector3 v1; Vector3 v2), and assign to them location of your 1st square/cube, and to 2nd vector3 - location/position of 2nd tile. and if (v1 == v2) then do what you want
Hey, thank you for your answer, I started creating the map by using x,y coordinates but than Unity presented their new tilemap-system, I wasn't able to access a single tile of the new system so I started to use the new system as background (grass) and put gameobjects on top of it so I can avoid to create 10.000 Gameobject when creating a tilemap 100x100 large but maybe this wasn't a good idea^^