Position of one object relative to another

Hello, I am just starting with Unity and I got stuck for a while with one, probably basic, thing. I usualy try to solve similar issues without asking (which leads to really ugly code :D), but sometimes it is really disappointing if you get stuck with simple thing for more time than necessary.

I have a function that is placing objects into another object , like if you filling a LargeBox with SmallBoxes. First I calculate position of First SmallBox (in the corner of empty LargeBox) and then just adding SmallBoxes. Since Im using just world position, this doesnt work when LargeBox is rotated.

Code is following:

Vector3 FirstSmallBoxPos = LargeBox.transform.position;
            FirstSmallBoxPos.y += LargeBox.Size.y;
            FirstSmallBoxPos.x += LargeBox.Size.x / 2 - SmallBox.Size.x / 2;
            FirstSmallBoxPos.z += LargeBox.Size.z / 2 - SmallBox.Size.z / 2;

            return FirstBoxPos; // postion of FirstSmallBox in the corner of the LargeBox

How does the code should look like when I want to work with rotated LargeBox? I guess, that key is in using local position intead of world one, but I really dont know how.

Thanks in advance!

@LynoHD, well to be honoust, I'm not an expert on the delegate either.You can see it as a variable where you contain a function in. Then you can call multiple functions from that function(I have not found out why it's handy yet). But I find the button clicks work perfectly with the delegate function in it.

1 Answer

1

You need to use the right reference frame. The way you’re using it above is in the world reference frame which will not change when the parent object rotates as you’ve experienced. In your case the reference frame you care about is the large box’s. So one easy to understand way to do it would be something like this:

Vector3 FirstSmallBoxPos = LargeBox.transform.position;
float xAmount = LargeBox.Size.x / 2 - SmallBox.Size.x / 2;
float yAmount = LargeBox.Size.y;
float zAmount = LargeBox.Size.z / 2 - SmallBox.Size.z / 2;
FirstSmallBoxPos += LargeBox.transform.up * yAmount; 
FirstSmallBoxPos += LargeBox.transform.right * xAmount; 
FirstSmallBoxPos += LargeBox.transform.forward * zAmount;