Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Aligning one game object to another for base building system considering different rotations based o

Discussion in 'Physics' started by Kiket1995, Nov 20, 2023.

  1. Kiket1995


    Nov 12, 2018
    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:

    visualization.transform.postion = currentHit.point + Vector3.Scale(visualization.Bounds.extents, currentHit.normal.normalized);

    This works only for right and straight angles, and becomes a problem when there are different rotations:

    Is there any way to know the distance based on renderer/collider size and object rotation, without using bounds?
  2. zulo3d


    Feb 18, 2023
    Place this script onto your camera and then click on an object to clone it.

    Code (CSharp):
    1. using UnityEngine;
    3. public class CloneObject : MonoBehaviour
    4. {
    5.    void Update()
    6.    {
    7.         if (Input.GetMouseButtonDown(0))
    8.         {
    9.             Ray ray=Camera.main.ScreenPointToRay(Input.mousePosition);
    10.             if (Physics.Raycast(ray,out RaycastHit hit,500f))
    11.             {
    12.                Vector3 scaledNormal=Vector3.Scale(hit.transform.localScale,hit.transform.InverseTransformVector(hit.normal));
    13.                GameObject obj=Instantiate(hit.transform.gameObject,hit.transform.position+hit.transform.TransformVector(scaledNormal),hit.transform.rotation);
    14.             }
    15.         }
    16.    }
    17. }
  3. Kiket1995


    Nov 12, 2018
    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.