- Home /
position of 2d sprites is way off
Hello I'm pretty new to unity and i have a problem with the placement of 2d sprites... Im trying to create a isometric grid and it kinda works, but the gaps between the cells is way to big. Here the code i use:
void CreateGrid()
{
grid = new GridCell[(int)size.x,(int)size.y];
for (int ix = 0; ix < (int)size.x; ++ix)
{
for (int iy = 0; iy < (int)size.y; ++iy)
{
float cell_x = ((ix - iy) * (GridCell.CELL_WIDTH / 2)); // CELL_WIDTH = 128
float cell_y = ((ix + iy) * (GridCell.CELL_HEIGHT / 2)); // CELL_HEIGHT = 64
float cell_z = 0;
Vector3 position = new Vector3(cell_x, cell_y, cell_z);
GridCell cell = Instantiate(gridCell, position, Quaternion.identity);
grid[ix, iy] = cell;
}
}
}
My Goal is to get a grid without gaps, that still could be used in world space....
Answer by Rhombuster · Apr 06, 2017 at 09:50 PM
I didn't quite understand what you were doing, but here is a simpler way:
void CreateGrid(float start_x, float start_y, float start_z) {
grid = new GridCell[(int)size.x, (int)size.y];
float current_cell_x = start_x;
float current_cell_y = start_y;
float current_cell_z = start_z; // Just in case you want to change it later
for(int y = 0; y < (int)size.y, y++) {
current_cell_x = start_x;
for(int x = 0; x < (int)size.x, x++) {
Vector3 position = new Vector3(current_cell_x, current_cell_y, current_cell_z);
GridCell cell = Instantiate(gridCell, position, Quaternion.identity);
grid[y, x] = cell;
current_cell_x += GridCell.CELL_WIDTH;
}
current_cell_y += GridCell.CELL_HEIGHT;
}
}
Just give it a starting x, y and z and it should tile it properly. This starts tiling from left to right, then bottom to top. If you'd like to switch directions, say going top down or right to left, you can just change the += operator to -=. I didn't test this, so let me know if it doesn't work.
Your answer
Follow this Question
Related Questions
How do I check if/where in a sprite another sprite is? 0 Answers
Setting children position to Vector3.zero doesn't make them go to center of parent? 1 Answer
Mouse position not returning actual position 0 Answers
Spawn objects at random position ON a 2D object. 1 Answer
Shoot second cell in 2d 0 Answers