I have a script that lets player move objects around with the mouse and when player clicks it will attach itself to the wall. In the above picture I have a cube that the player has attached to a wall, however half of the cube goes inside the wall. I don’t want that, the cube should be fully visible and attached to the wall.
Here’s the code that I currently use, any help is appreciated.
//If the object is wall furniture run code.
else if (currentfurniture.gameObject.tag == "WallFurniture")
{
//If not already holding an object run this code.
if (!HoldingObject)
{
nowyoucanrun = false;
Vector3 m = Input.mousePosition;
m = new Vector3(m.x, m.y, transform.position.y);
Vector3 p = Camera.main.ScreenToWorldPoint(m);
//Object follows cursor
currentfurniture.position = new Vector3(p.x, 5, p.z);
if (Input.GetMouseButtonDown(0) && nowyoucanrun == false)
{
//fm._canvas1.SetActive(true);
RaycastHit[] hits = new RaycastHit[4];
//Fire multiple rays to find shortest distance
Physics.Raycast(currentfurniture.position, Vector3.forward, out hits[0]);
Physics.Raycast(currentfurniture.position, Vector3.back, out hits[1]);
Physics.Raycast(currentfurniture.position, Vector3.left, out hits[2]);
Physics.Raycast(currentfurniture.position, Vector3.right, out hits[3]);
//Check array to find shortest distance and hit.
float smallestdist = hits[0].distance;
RaycastHit target = hits[0];
foreach (RaycastHit t in hits)
{
if (t.distance < smallestdist)
{
smallestdist = t.distance;
target = t;
}
}
Debug.Log(smallestdist);
Debug.Log(target.transform.name);
//Set position of cube
currentfurniture.position = new Vector3(target.point.x, 5, target.point.z);
camera.cameraFreezerot = false;
HoldingObject = false;
nowyoucanrun = true;
currentfurniture = null;
}
}