Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Grid based Object creation

Discussion in 'Scripting' started by King09, Nov 8, 2018.

  1. King09

    King09

    Joined:
    Dec 22, 2017
    Posts:
    4
    I want to control the objects being created based of the point hit by the raycast.

    I snap the object to the grid and round it out like:

    Code (CSharp):
    1. Vector3 newPos = hitInfo.point
    2.  
    3. newPos.x = Mathf.Round(newPos.x / snapvalue) * snapvalue;
    4.  
    5. newPos.z = Mathf.Round(newPos.z / snapvalue) * snapvalue;
    6.  
    7. newPos.y = Mathf.Round(newPos.y / snapvalue) * snapvalue;
    8.  
    But when the ray cast hits the block on the side I want it to be created in the front or back but it seems as the cursor object goes into said object and creates it there. But works on the left and right and back just not the front side what should I do to go from the hit.point out in a straight line to basically create on the sides.
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,066
    Add the hit.normal ( * 0.5 * unitSize) to hit.point to get a better spot to apply the rounding to
     
  3. King09

    King09

    Joined:
    Dec 22, 2017
    Posts:
    4
    Even after doing that I get after effect's and the box prefab just teleport's to incorrect positions, I need them to be able to be created on all side's sort of like minecraft block placement.
     
  4. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,066
    Yea, thats exactly what i was guessing, and this is exactly how i have done it in the past
    hit.point on the side of a cube is a position that is exactly half way between one grid point and the next, so you add the hit.normal to the hit.point to get into the adjacent cell
     
    King09 likes this.
  5. King09

    King09

    Joined:
    Dec 22, 2017
    Posts:
    4
    So to clarify it turns out it was the pivot point of the mesh it had to be [centered] if it's not it causes artifacts with the positions so you wasnt wrong and I added that little peice of code you gave me to my game much appreciated!.