Home > Mobile >  How do I check if a tree object is really close to another in unity?
How do I check if a tree object is really close to another in unity?

Time:05-01

I have been making a survival game in unity and I have generated the trees with the below function

The GenerateTree function

void GenerateTree(int x, int y)
    {
        //define our tree

        //generate log

        int treeHeight = Random.Range(minTreeHeight, maxTreeHeight);
        for(int i = 0; i < treeHeight; i  )
        {
            PlaceTile(log, x, y   i);
        }

        //generate leaves
        PlaceTile(leaf,x,y treeHeight);
        PlaceTile(leaf, x, y   treeHeight 1);
        PlaceTile(leaf, x, y   treeHeight 2);

        PlaceTile(leaf, x-1, y   treeHeight);
        PlaceTile(leaf, x-1, y   treeHeight 1);

        PlaceTile(leaf, x   1, y   treeHeight);
        PlaceTile(leaf, x   1, y   treeHeight   1);

    }

The PlaceTile function

 public void PlaceTile(Sprite tileSprite, int x, int y)
    {
        GameObject newTile = new GameObject();

        float chunkCoord = (Mathf.Round(x / chunkSize) * chunkSize);
        chunkCoord /= chunkSize;
        Debug.Log(chunkCoord);
        newTile.transform.parent = worldChunks[(int)chunkCoord].transform;

        newTile.AddComponent<SpriteRenderer>();
        newTile.GetComponent<SpriteRenderer>().sprite = tileSprite;
        newTile.name = tileSprite.name;
        newTile.transform.position = new Vector2(x   0.5f, y   0.5f);

        worldTiles.Add(newTile.transform.position - (Vector3.one * 0.5f));
    }

But I have a problem when trees spawn like that

I believe I need to use a if statement to check if another log is close by, but I need help of how to do that.

CodePudding user response:

Vector2.Distance(Vector2D,Vector2D)

https://docs.unity3d.com/ScriptReference/Vector2.Distance.html

if(Vector2.Distance(Log1Location,Log2Location) > 10)
{
   //Spawn?!
}
  • Related