- Home /
 
 
               Question by 
               CyanSlinky · Nov 17, 2017 at 10:57 PM · 
                gridsnapsnappingedgeedge detection  
              
 
              Snap to grid edge midpoints?
Hey, I managed to get grid snapping to work, but i have no idea how to snap to the middle of the edges of the grid, any help would be appreciated.
This is how im snapping to the grid :
 gridPosition = new Vector3(Mathf.RoundToInt(position.x / gridSize) * gridSize, 0,
                            Mathf.RoundToInt(position.z / gridSize) * gridSize);
 
               what i want is essentially to snap to the red points below, i just don't really know how to round to those points

 
                 
                gridmid.png 
                (64.2 kB) 
               
 
              
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by CyanSlinky · Nov 18, 2017 at 03:14 PM
Alright i found a solution, here it is for posterity
 gridHitPos = new Vector3(Mathf.RoundToInt(hitPos.x / gridSize) * gridSize, 0,
                          Mathf.RoundToInt(hitPos.z / gridSize) * gridSize);
 
 cornerHitPos = new Vector3(Mathf.FloorToInt(hitPos.x / gridSize) * gridSize, 0,
                            Mathf.FloorToInt(hitPos.z / gridSize) * gridSize);
 
 Vector3 localPos = hitPos - cornerHitPos;
 midHitPos = cornerHitPos;
 
 if( localPos.z < gridSize / 2.0f )
 {
     if( localPos.x > localPos.z && gridSize - localPos.x > localPos.z )
     {
         midHitPos.x += gridSize / 2.0f;
     }
     else if( localPos.x > gridSize / 2.0f )
     {
         midHitPos.x += gridSize;
         midHitPos.z += gridSize / 2.0f;
     }
     else
     {
         midHitPos.z += gridSize / 2.0f;
     }
 }
 else
 {
     if( localPos.x < localPos.z && gridSize - localPos.x < localPos.z )
     {
         midHitPos.x += gridSize / 2.0f;
         midHitPos.z += gridSize;
     }
     else if( localPos.x > gridSize / 2.0f )
     {
         midHitPos.x += gridSize;
         midHitPos.z += gridSize / 2.0f;
     }
     else
     {
         midHitPos.z += gridSize / 2.0f;
     }
 }
 
              Your answer
 
             Follow this Question
Related Questions
Grid snapping 0 Answers
Create Grid and Snap Rigidbodies to Grid 1 Answer
Is there a way to check if something was snapped on a specific grid? 1 Answer
cannot get snap to grid to activate 0 Answers
Snap to grid not working for me 1 Answer