In Game Building Grid leaving exactly one grid sized gap in bettween objects

So I’ve tried to design a grid based building system however I’m getting a strange bug when when using raycasts and normals to place the objects. From some angles it works exactly as intended and from others it leaves an odd gap.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Grid : MonoBehaviour {

    public Transform slave;
    public Text Output;
    public float GridSize = 1;
    public float Distance = 2;

	// Use this for initialization
	void Start () {
    }

    RaycastHit hit;
    Vector3 point = new Vector3(),mouse = new Vector3();
	// Update is called once per frame
	void Update () {

        if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit))
        {
            if (Vector3.Distance(Camera.main.transform.position,hit.point) > GridSize)
            {
                Vector3 pos = new Vector3(Mathf.Round(hit.point.x),Mathf.Round(hit.point.y),Mathf.Round(hit.point.z));
                //pos = pos - Player.forward * -0.1f;
                //pos = pos * GridSize;
                slave.position = pos+hit.normal;
                Output.text = hit.normal.ToString();
                
            }

            
        }

        if(Input.GetMouseButtonDown(0))
        {
            Transform copy = Instantiate(slave);
            copy.GetComponent<Renderer>().material.color = Color.red;
            copy.gameObject.AddComponent<BoxCollider>();
        }
	}
}

100410-screenshot-1.png

So from this angle it seems to work as intended

However from here it doesn’t

100411-screenshot-1.png

Been on this for 2 days so any help is appreciated

So for anyone else having the same issue i just worked out how to fix it. I believe it was a combination of a rounding issue and a hit point accuracy issue.

The rounding issue was fixed by writing a custom function.

float RoundUp(float a)
 {
     return (float)Math.Round(a, MidpointRounding.AwayFromZero);
 }

I fixed the issue with the hit point by first checking if the 2 “blocks” were going to end up in the same space if they were i then added the hit normal to move it.

Vector3 pos = new Vector3(RoundUp(hit.point.x*GridSize)/GridSize,RoundUp(hit.point.y*GridSize)/GridSize,RoundUp(hit.point.z*GridSize)/GridSize);

if(pos == hit.transform.position)
{
  pos += hit.normal*(1/GridSize);
}
slave.position = pos;

Hope it helps.