# Scale and position object between two points

Hi

I am working on a simple level editor for my 2D game and I want to be able to create the ground by just setting two points and then it creates a ground object between those two points. So it would scale the object to fit between the points and the position itself in the center of the two points to fit the grid. The object should also scale on both the X axis and Y axis.

This is my code as of right now.

``````void SpawnGround(Vector3 startPos, Vector3 endPos)
{
GameObject ground = Instantiate(objectsList.objects[selectedObject].prefab);
Vector3 centerPos = new Vector3(startPos.x + endPos.x, startPos.y + endPos.y);

float scaleX = Vector3.Distance(new Vector3(startPos.x, 0, 0), new Vector3(endPos.x, 0, 0));
float scaleY = Vector3.Distance(new Vector3(0, startPos.y, 0), new Vector3(0, endPos.y, 0));
ground.transform.position = centerPos;
ground.transform.localScale = new Vector3(scaleX, scaleY, 1);
}
``````

I can not get this code to work the way I want it to. Right now the position completely off when I create the object and the scale is also a bit off sometimes. The scale should also be rounded to either a full number (like 1, 2, 3 etc.) or half numbers (like 0.5, 1.5 etc).

I am not sure what I can do to fix this. Any help is appreciated!

You need to average the two vectors to find your center, something like this:

``````Vector3 centerPos = new Vector3( startPos.x + endPos.x, startPos.y + endPos.y ) / 2f;
``````

As far as scale, your code seems reasonable as long as a scale of x=1,y=1 corresponds to an actual in-game Vector3.Distance of x=1 and y=1.

Note that you don’t need a Vector3.Distance call if you’re only comparing 1 variable in each vector. This will work just as well:

``````Mathf.Abs(startPos.x,endPos.x)
``````

Rounding can be accomplished easily with Mathf.Round():

For rounding to nearest 0.5:
http://stackoverflow.com/questions/1329426/how-do-i-round-to-the-nearest-0-5