I am creating base building system similiar to Valheim’s one, but I have problems with aligning objects towards themselves. I want to be able to place object with different rotation at point my camera is looking and make them stick to other objects, like in classic base building system.
I tried to determine the distance I need to move the object from the raycast hit point based on mesh renderer bounds size like below:
Place this script onto your camera and then click on an object to clone it.
using UnityEngine;
public class CloneObject : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray,out RaycastHit hit,500f))
{
Vector3 scaledNormal=Vector3.Scale(hit.transform.localScale,hit.transform.InverseTransformVector(hit.normal));
GameObject obj=Instantiate(hit.transform.gameObject,hit.transform.position+hit.transform.TransformVector(scaledNormal),hit.transform.rotation);
}
}
}
}
Thats not exactly what i wanted to achieve, but i managed to solve my problem.
This may not be the best way to do this, but it is working as intended.
I used normal from currentHit to cast another ray toward placeable element, then my result is raycast hit on it’s surface, then i take distance between placeable element’s pivot and surface hit, multiplying currentHit normal by this distance make objects do not intersect.