- Home /
Round an object's position based on its scale
I have a building game where you can choose to have what you place to be basically aligned to a grid by rounding its position. I achieve that with this little bit of code: transform.position = new Vector2(Mathf.Round(transform.position.x), Mathf.Round(transform.position.y));
The problem is, this just rounds it to the nearest whole number, resulting in placing objects smaller or larger than 1x1 to align incorrectly, as shown in this image:
How can I change my code for it not to do this?
Answer by highpockets · Feb 27, 2021 at 08:42 PM
Well it really depends on your grid. If you have a grid with items spaced evenly with a distance of 1 unit between each item, and starting at the world origin, then you would just round your number to the nearest whole numbers, but it is a lot nicer to be able to dynamically change things. UNTESTED
public int rows;
public int cols;
public float spread;
Vector2[,] grid = [cols, rows];
void Start()
{
for(int i = 0; i < cols; i++)
{
for(int j = 0; j < rows; j++)
{
grid[i,j] = new Vector2(spread * (float)i, spread * (float)j);
}
}
}
//iterate through the grid items to find the closest
public Vector2 FindClosestItem(Vector2 pos)
{
Vector2 closest = grid[0,0];
float shortestDist = spread * (float)rows;
for(int i = 0; i < cols; i++)
{
for(int j = 0; j < rows; j++)
{
float dist = Vector2.Distance(grid[i,j], pos);
if(dist <= shortestDist)
{
shortestDist = dist;
closest = grid[i,j];
}
}
}
}
//alternatively you could just calculate based on the spread but this does not take bounds into account, though it could with a couple modifications. This would be the more optimized approach depending on how big the grid.
public Vector2 CalculateClosest(Vector2 pos)
{
float xRemainder = pos.x % spread;
float yRemainder = pos.y % spread;
float yOffset = (yRemainder >= spread * 0.5f) ? spread - yRemainder : -yRemainder;
float xOffset = (xRemainder >= spread * 0.5f) ? spread - xRemainder : -xRemainder;
return new Vector2(pos.x + xOffset, pos.y + yOffset);
}
Thank you! The CalculateClosest function worked perfectly for this!
Your answer

Follow this Question
Related Questions
Problem at 180 degrees when rotating slowly 1 Answer
Find the difference between the Z rotation of two GameObjects 2 Answers
Clamp rotation of sprite? 0 Answers
Make my mathf to Wait? :) 2 Answers
2D Animation does not start 1 Answer