Hi guys. I’ve got some rectangle drawed with mouse
Vector3 topLeft = Vector3.Min(startPosition, endPosition);
Vector3 bottomRight = Vector3.Max(startPosition, endPosition);
Rect rect = Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
and I’m trying to convert it into some gameobject by instantiating a prefab (basically a quad with attached mesh to it):
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(new Vector3(rect.center.x, rect.center.y, 5));
GameObject go = (GameObject) Instantiate(prefab, worldPoint, Quaternion.identity);
It centers perfectly, but how do I resize it to fit exactly to the size of drawed rectangle?
I can’t wrap my head around it. Any ideas?
Ok, I’ve figured it out. Here’s a solution if anybody else will stumble upon such problem.
Mesh mesh = go.GetComponent<MeshFilter>().mesh;
Bounds bounds = mesh.bounds;
//Getting xMin and yMin
Vector3 min = new Vector3(rect.xMin, rect.yMin, 0);
Vector3 max = new Vector3(rect.xMax, rect.yMax, 0);
//Converting them to worldspace coordinates
min = Camera.main.ScreenToWorldPoint(min);
max = Camera.main.ScreenToWorldPoint(max);
//Calculating width/height in world space coorinate-size
float width = max.x - min.x;
float height = max.y - min.y;
//Calculating scale factors
float widthScaleFactor = (width / bounds.size.x);
float heightScaleFactor = (height / bounds.size.y);
Vector3 localScale = go.transform.localScale;
localScale.x *= widthScaleFactor;
localScale.y *= heightScaleFactor;
go.transform.localScale = localScale;
Probably not the prettiest one, but it works.
Assuming the quad mesh’s dimensions are 1x1 units, you could set the instantiated object’s transform’s scale to be the same as the Rect’s width and height.
go.transform.localScale = new Vector3(rect.width, rect.height, 1);
This works pretty well, but its off when the models origin is not a center.