I am really struggling with placing objects exactly where I want to relative to other objects. In my game I have a ‘door’ object and I want to spawn a room behind it when the door is clicked on. Each room has 4 exits, one on each side, and I am having a lot of trouble getting the room to spawn with correct orientation in regards to the facing of the door. I was at one point getting it to spawn on-mark, but it had the wrong rotation.
Rooms might not always be the same size, so I need to take collider bounds into account. This basically need to work pretty purely off of the objects positions and orientations with no hard-coding of offsets. A final adjustment can be made in the code spawning the room type but that has to be known ahead of time and work for every case (such as adding in a -y coordinate for basement rooms, etc). Sorry for all these odd requirements but it really is what I’m after.
I created the following as a test. When the cube on the left has no rotation the blocks will line up center to center as expected. (though it says floor I do mean ‘center’ as in a correct sideways T shape) However when the first (left) cube is rotated the positions are maligned.
What code can I use to place the second cube correctly? Any help with code or prefab construction tips is greatly appreciated. Having a lot of difficulty fully and completely understanding how object placement works. I feel like this should be easier and that I’m missing something.
Thank you!!!
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
// Use this for initialization
void Start () {
doStuff();
return;
}
public void doStuff() {
Debug.Log(gameObject.transform.forward);
GameObject nextRoom = (GameObject)Instantiate(Resources.Load("vectortests/Floor"));
//now that position needs to be offset by half the room size
Vector3 newRoomSize = nextRoom.transform.GetComponent<Collider>().bounds.size;
Vector3 newRoomOffset = newRoomSize *= 0.5f;
Debug.Log("Position before halved room offset is added: " + gameObject.transform.position);
//now add that offset to the position
Vector3 newRoomPos = gameObject.transform.position + newRoomOffset;
Debug.Log("Position after halved room offset is added: " + newRoomPos);
//now that has to be multiplied by the vector
Vector3 doorForward = gameObject.transform.forward;
Debug.Log("Forward is found to be: " + doorForward);
newRoomPos = Vector3.Scale(newRoomPos, doorForward);
Debug.Log("Final Position: " + newRoomPos);
nextRoom.transform.position = newRoomPos;
nextRoom.transform.rotation = gameObject.transform.rotation;
}
}