Search Unity

Resolved Snapping Like Space Engineers

Discussion in 'Scripting' started by peter17451, Aug 4, 2020.

  1. peter17451

    peter17451

    Joined:
    Dec 12, 2019
    Posts:
    2
    Hello! I'm currently working on a building game, and I'm trying to implement object snapping based on distance.
    I've provided a reference video that shows sort of what I want:
    I want to be able to place any block freely, but if the placing "preview" comes close enough to any other block they should snap together.

    This is currently what I have:
    Code (CSharp):
    1.  
    2. CurrentPosition = Camera.main.transform.position + (Camera.main.transform.forward * 5.0F);
    3. CurrentRotation = Camera.main.transform.rotation;
    4.  
    5. foreach (Collider other in Physics.OverlapBox(CurrentPosition, Vector3.one * 2.0F, CurrentRotation))
    6. {
    7.     if (other is BoxCollider)
    8.     {
    9.         Vector3 diff = (CurrentPosition - other.transform.position).normalized * 2.0F;
    10.         CurrentPosition = other.transform.position + diff;
    11.         CurrentRotation = other.transform.localRotation;
    12.     }
    13. }
    It sort of works, except that the forward axis doesn't snap.
    I should mention that I want to be able to stop the blocks from snapping if the camera moves far enough away.

    Reference Video:


    If anyone can help me it would be great :)
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Do a raycast from the camera to the center of the screen. If you hit a cube, simply position your preview cube at the next grid position in the direction of the raycast hit normal.

    You can also use the overlapping box trick to check if any "free placed" block would be touching another block and simply disallow it. That seems to be what's happening from the video you shared if the venter of the screen was not over an existing block. Correct me if I'm wrong there though.
     
  3. peter17451

    peter17451

    Joined:
    Dec 12, 2019
    Posts:
    2
    Thank you very much! Completely forgot about raycasting. Totally solved my issue!