Instantiating A Prefab Onto Another Prefab at Relative Rotation

Hi there!

Again, thanks to this forum for all of your help.

I am trying to figure out how to instantiate an object onto another object via raycast, but have the rotation oriented relative to the object is it being placed on. I have the script far enough along to place objects onto other objects, but they always keep the prefab’s original rotation. I assume this is done through quaternions?

For instance, I have a wall that I want to hang a picture on. The wall is already there in the scene, and I raycast on mouseclick to instantiate the picture onto the wall, but the rotation needs to be relative to the wall (e.g. flat against it).

Hopefully this makes sense. I have some code for my script, but I’m not sure how much it will help:

	void Update() {
		bombs = GameObject.FindGameObjectsWithTag ("Bombs");
		explosions = GameObject.FindGameObjectsWithTag ("Explosions");
		if (Input.GetMouseButtonDown (0)) 
		{
			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast (ray, out hit, 5)) 
			{
				Instantiate (TNT, hit.point, Quaternion.identity);
			}
		}
	}

As always, you guys are awesome!!!

The right solution will depend on the nature of the game object you are placing. In particular it will depend on what side of that object you consider the ‘front’. Say the objects is a Quad in which the backside is the forward facing side:

  if (Physics.Raycast (ray, out hit, 5)) {
             Quaternion q = Quaternion.FromToRotation(-transform.forward, hit.normal);
             Instantiate (TNT, hit.point+hit.normal*0.01f, q);
  }

Note this will place the object flat on the surface with the pivot point just in front of the surface. Note the ‘+hit.normal*0.01f’.