- Home /
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!
Answer by Bennett-Lynch · Apr 17, 2016 at 04:56 PM
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(): http://docs.unity3d.com/ScriptReference/Mathf.Round.html
For rounding to nearest 0.5: http://stackoverflow.com/questions/1329426/how-do-i-round-to-the-nearest-0-5
Thank you! After your help, I managed to fix all of it! :)
Here's my code if anyone is interested.
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) / 2;
float scaleX = $$anonymous$$athf.Abs(startPos.x - endPos.x);
float scaleY = $$anonymous$$athf.Abs(startPos.y - endPos.y);
centerPos.x -= 0.5f;
centerPos.y += 0.5f;
ground.transform.position = centerPos;
ground.transform.localScale = new Vector3(scaleX, scaleY, 1);
}
Your answer
Follow this Question
Related Questions
How do you move an object relative to a plane's global scale? 3 Answers
Position + Vector3 doesn't return correct values 1 Answer
How do I drop a GameObject on top of Grid/mesh's Vector3 coordinates? 0 Answers
Enemy Jitters when i want him to stop a certain distance 0 Answers
Why does my object disappear? 1 Answer