Search Unity

Cube placing on edges of cubes

Discussion in 'Scripting' started by Senpai_Remling, Mar 18, 2019.

  1. Senpai_Remling

    Senpai_Remling

    Joined:
    Dec 5, 2016
    Posts:
    1
    Hey,

    For a game i make i currently work on a building mechanic. i've got everything working just fine, just one little thing i cant figure out how to avoid.

    The problem is, if you loot at the edge of a cube you placed you will place a cube that is floating in the air without beeing "connected" to another cube.

    here an image for better understanding:



    here is the code that is responsible for the cube placement:

    Code (CSharp):
    1. if (Physics.Raycast(ray, out raycasthit, placeRange))
    2. {
    3.     if (raycasthit.transform.gameObject.tag == "Block" || raycasthit.transform.gameObject.tag == "Ground")
    4.     {
    5.         if (mode == 0)
    6.         {
    7.             Vector3 hitpoint = ray.GetPoint(raycasthit.distance - 0.2f);
    8.  
    9.             float ypos = ((hitpoint.y % 1 != 0) ? Mathf.FloorToInt(hitpoint.y) : hitpoint.y) + 0.5f;
    10.  
    11.             Vector3 placeAt = new Vector3(Mathf.RoundToInt(hitpoint.x), ypos, Mathf.RoundToInt(hitpoint.z));
    12.             blockPlaceholder.transform.position = placeAt;
    13.             blockPlaceholder.SetActive(true);
    14.         }
    15.     }
    16. }
    17.  
    18. if (Input.GetMouseButtonDown(0))
    19. {
    20.     if(mode == 0)
    21.     {
    22.         GameObject newblock = Instantiate(block, blockPlaceholder.transform.position, Quaternion.Euler(Vector3.zero));
    23.     }
    24. }

    Ignore the "mode". This is a very cutdown version of the script since there is a lot of other stuff in there too.



    i include the whole package too so you can test it out and change stuff easier.

    would love to get some ideas on how to avoid this.
     

    Attached Files:

  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Raycast down from the cube you're about to place by 1 cube length distance and if there's nothing there, don't place the original cube?