How to get vector3 grid position for object dynamically
Hi, I want to create a simple algorithm for placing cubes with grid positioning. I know it's easy with pre calculated positions and spawn cubes around it with triple loops but what I want to achieve is every time I request position from a function, It should return me the vector position for it dynamically.
For example: row size = 2, and starting point is Vector3.zero.
1. Vector3(0,0,0);
2. Vector3(1,0,0);
3. Vector3(0,0,1);
4. Vector3(1,0,1);
5. Vector3(0,1,0);
6. Vector3(1,1,0);
7. Vector3(0,1,1);
8. Vector3(1,1,1);
It should return values like this. Anyone has an idea about this? Here what I tried so far but it places objects same poisition with some pattern I could not understand.
public Vector3 GetNextPos()
{
Vector3 nextPos;
if (itemCountInRowX < rowSize)
{
nextPos = new Vector3(currentX, currentY, currentZ);
currentX += cubeSize;
itemCountInRowX++;
}
else if (itemCountInRowX == rowSize && itemCountInRowZ < rowSize)
{
currentX = startPos.x;
currentZ += cubeSize;
nextPos = new Vector3(currentX, currentY, currentZ);
if (itemCountInRowZ == 0)
itemCountInRowZ = 2;
else
itemCountInRowZ++;
itemCountInRowX = 0;
}
else if (itemCountInRowX == rowSize && itemCountInRowZ == rowSize)
{
itemCountInRowX = 0;
itemCountInRowZ = 0;
currentY += cubeSize;
currentX = startPos.x;
currentZ = startPos.z;
nextPos = new Vector3(currentX, currentY, currentZ);
}
else
nextPos = Vector3.zero;
return nextPos;
}
Answer by TheMemorius · Oct 24, 2021 at 01:48 PM
Does the order of the returned positions have to be exactly like the example you gave (like (0, 0, 1) coming directly after (1, 0, 0) etc.)? If not, this code will create a new cube in a 3d grid each time you click the button:
using UnityEngine;
class SpawnTest : MonoBehaviour
{
public int RowSize = 2;
public float CubeSize = 1.5f;
private int _count = 0;
public Vector3 GetNextPos()
{
int x = _count % RowSize;
int y = (_count / RowSize) % RowSize;
int z = (_count / RowSize) / RowSize;
++_count;
if(_count >= Mathf.Pow(RowSize, 3))
_count = 0;
return new Vector3(x, y, z) * CubeSize;
}
private void OnGUI()
{
if(GUI.Button(new Rect(10, 10, 100, 50), "Create next cube"))
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = GetNextPos();
}
}
}
The magic word here is modulo
.
Thank you for the answer. Order is important for me but I'll take it from here and try to do it myself. This is very helpful.
Your answer
Follow this Question
Related Questions
Approach for filling 6x6 matrix with shapes 2 Answers
Positioning Screen Space UI element in center of a grid square? 1 Answer
Snap object to grid made from cubes during runtime 0 Answers
Connecting Pods/Nodes together on a grid using pathfinding? 0 Answers
Generate 3d Mesh from 2d drawing 0 Answers