convert from world to voxel when 1 voxel doesn't equal 1 unity unit

I’m making a game which requires using a voxel engine to build structures, except I plan to include more models than just simple cubes, and some of these are quite small. So I need to the voxels to be smaller than 1 unity unit each (3 per unit). The problem is I’m having trouble converting between world space and voxel coordinates due to the unequal sizes (if they were the same size it wouldn’t be a problem). This is what I’ve tried so far:

    public Vector3 GetIndexFromWorld(Vector3 worldPos, Vector3 normals) {
        float half = ((1f / (float)VoxelsPerMeter) / 2f); // VoxelsPerMeter equals 3
        Vector3 localPos = transform.InverseTransformPoint(worldPos);
        Vector3 point = localPos + normals * -half;
        return new Vector3(Mathf.RoundToInt(point.x) * VoxelsPerMeter, Mathf.RoundToInt(point.y) * VoxelsPerMeter, Mathf.RoundToInt(point.z) * VoxelsPerMeter);
    }

Thanks in advance for any help.

What's InverseTransformPoint for -- Do your objects run diagonally?

–

I have the InverseTransformPoint to convert from world space to the chunks local space, because the chunk contains the 3D array of voxels (and yea, to give the option of rotating the chunks).

–

1 Answer

1

Isn’t it just:

var localPos = transform.InverseTransformPoint(worldPos) * VoxelsPerMeter;
return new Vector3(Mathf.FloorToInt(localPos.x),Mathf.FloorToInt(localPos.y),Mathf.FloorToInt(localPos.z));

Though I'd prefer a Tuple for the index. Tuple<int,int,int>

–

Thanks whydoidoit. multiplying the local position by three, replacing "RoundToInt" with "FloorToInt", and removing the * VoxelsPerMeter from the final vector3 solved it.

–

Will convert this lot to an answer so you can tick it :)

–

How would you figure out how many voxels per meter? If the object scales, won't that change?? @nug700 @whydoidoit

–