# instantiate prefabs randomly over a polygon collider 2D bounds

I’m trying to instantiate trees over a mountain sprites randomly.

what I did is to add a polygon collider 2D component to the mountain sprite
this generates a bounds.

I’m writing a script to instantiate tree (prefab) randomly over the mountain top edge.

my question is, how do I get the coordinates (positions) from that top bound of the polygon collider?

for example, if the size.x of this mountain polygon collider is 100.

in every 10 distance at x axis, I’d like to pick a y offset from its edge (bound), then place a tree to that position. so the bottom of the tree always at edge of that mountain top

Therefore, I’m actually looking for a way to find the bounds y axis poistion by its related x axis position, say the total size.x of the collider is 100, when at x axix 50, how do I find its top edge y axis?

Raycasting from above your object down is probably the easiest as it avoids complications if you change from a PolygonCollider and all the maths is done for you.

Basically the idea is, get your collider, find it’s largest y value from the bounds, go up a little more, raycast directly downwards.

Untested but the following might get you close, the arg I give is xOffset which is a distance along the x axis from the leftmost point of the collider, so it’s not in world units, you might want to change that depending on your usage.

Note the Nullable type is from System I think, you can’t return null values for structs normally but in this case it seems reasonable to return a null value if there is no relevant top point.

``````using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TopPoint2D : MonoBehaviour
{

private new Collider2D collider;

void Start()
{
collider = GetComponent<Collider2D>();

Debug.Log(GetTopPoint(0));
Debug.Log(GetTopPoint(1));
Debug.Log(GetTopPoint(5));
Debug.Log(GetTopPoint(10));
Debug.Log(GetTopPoint(11));
}

private Nullable<Vector2> GetTopPoint(float xOffset){
// a point on the y axis that is always above our collider
float yStrictlyAbove = collider.bounds.max.y + 0.1f;

float xMin = collider.bounds.min.x;

float yStrictlyBelow = collider.bounds.min.y - 0.1f;
float distance = yStrictlyAbove - yStrictlyBelow;

RaycastHit2D[] hits = Physics2D.RaycastAll(
new Vector2(xMin + xOffset, yStrictlyAbove),
Vector2.down,
distance: distance
);

foreach(RaycastHit2D h in hits){
if(h.collider == collider){
return new Nullable<Vector2>(h.point);
}
}

return null;
}
}
``````

@Scribe thank you so much, this is exactly what I was looking for, I actually started making complicate math that you have mentioned in your answer. Your solution is way clear!

@Scribe I wanted to spawn prefab instances randomly over a polygonal collider, but as being in a 2D top-down view game, not above mountains or something…can you help in my case?