How to place a Painting on a Wall

Hi everyone,

I would like to be able to place a rectangular object (imagine a painting) onto a wall in a room from a distance.

For example: imagine you are the character/player standing in the middle of a room. I would like to be able to instantiate a rectangle from a distance upon a “Fire1” event and have it framed onto the wall without having the painting fall down (0 gravity rigidbody). I would like the painting to be positioned up-right and I would like the side of the painting with the largest surface area to be attached to the wall.

How is this done? I imagine there needs to be some kind of use of RayCasting in order to achieve this.

  1. Ray Casting calculation using Physics.RayCast and RayCastHit (Unity - Scripting API: RaycastHit)

  2. There will need to be a Prefab object for the rectangular object. I suppose the object does not need to have a RigidBody component attached to it. I would like this to be dynamic so that the painting can be planted on any flat surface. For example: Left Wall, Right Wall, Forward Wall, Rear Wall, Floor, Ceiling

Any help will be appreciated.
Thanks.

Here is a code snippet of what I am intending to do. For some reason the object that I am instantiating is not using the largest surface area to “attach” to the wall. When I am facing a certain wall, the effect will work.

void Update () 
{
		RaycastHit hit;
		Vector3 fwd = transform.TransformDirection(Vector3.forward);
		
		// If RayCast is pointing at an object AND fire button is selected, create painting
		if(Physics.Raycast(transform.position, fwd, out hit, 1000.0f)  
		   Input.GetButtonDown("Fire1"))
		{
				Instantiate(my_prefab_object, hit.point, Quaternion.identity);
                }
}

Am I missing the use of Ray Cast Normals?

Instantiate(my_prefab_object, hit.point, Quaternion.identity);

This means to create an object, at the hit point where the rotation is the default rotation in Unity. It appears you are not taking rotation into account.

Lets take something like that into account…

GameObject obj = Instantiate(my_prefab_object, hit.point, Quaternion.identity);
obj.transform.LookAt(hit.point + hit.normal);

By adding the second line, we are now defining a rotation. It is told to look at the opposite direction that the hit was. This means that it is facing outward. In your 3d program, simply create your frame as if you can see the picture from the front of it.

1 Like