Unity 3D: How to make object stack on top of each other and check for acquired space?

Viewed 58

im bad at explaining so i ill ask through this picture, what i want to do is, when the player hits the gameobject(cube) i want it to transform.position to different place and start getting stacked on top of each other. now i get the transform part, i can do it by onCollisionEnter and then move the object to the place. but thats it, i can only do it for one object as others will keep moving inside of each other, now i want them to check if the place is acquired and then stack on top of the one that is already there, and if there are 3 cubes stacked on top of each other already then move to the next location beside them. Also, this is all in 3D. enter image description here

1 Answers

I would create a 2d arrays, or a jagged array.

Go to jagged array or 2d arrays to learn more

Basically if you know what an array is, it is a set of information. A jagged array is a set of arrays that can have varying lengthed arrays. A 2d (you can do 3d, 4d, 5d, so on) is an array of arrays of all the same length.

So basically if you want each stack to be the same length, use a 2d array, if they can vary in height, use a jagged array.

In this example I am going to use a 2d array.

Vector3 start = new Vector3 (0, 0, 0); //the stack starts here

Vector3 stackOffset = new Vector3 (2, 0, 0); //each stack is 2 units right
Vector3 heightOffset = new Vector3(0, 1, 0); //each object is 1 unit higher.
bool[3][5] stacks = new GameObject[3][5]; //3 stacks of 5 height

void OnCollisionEnter(Collision obj)
{
    if (obj.tag == "thing")
    {
        for (int i = 0; i < stacks.Length; i++)//loop 3 times (3 stacks)
        {
            for (int ii = 0; ii < stacks[].Length; ii++) //loop 5 times (5 in each stack)
            {
                if (stacks[i][ii] == false)
                {
                    stacks[i][ii] = true;
                    obj.transform.position = start + (i * stackOffset) + (ii * heightOffset);
                    return;
                }
            }
        }
        print("all stacks filled");
    }
}

Hope this works, if you have any errors, can you tell them to me in comments, or edit original post with an image.

Related