Converting Terrain:ReadVoxel() to WorldSpace

I am currently using Terrain:ReadVoxel() to get the voxels around the player, I then detect the voxels using the material. The only issue i’m having is getting the position of the detected voxel in worldspace.

Current Code for detecting voxels:

local region = Region3.new(C1, C2) -- C1 and C2 are worldspace vectors
local materials, voxels = Terrain:ReadVoxels(region, 4)
local size = voxels.Size

-- Looping through the voxels
for x = 1, size.X, 1 do
	for y = 1, size.Y, 1 do
		for z = 1, size.Z, 1 do
			local material, voxel = materials[x][y][z], voxels[x][y][z]
			if material == Enum.Material.Water then
				print("Found Voxel")
                -- Issue: How do I get the position of the voxel
				return true
			end
		end
	end
end

Currently the only things i know is that material[1][1][1] would be the C1 position, i’m just struggling with using that information to convert them all. Any help is greatly appreciated!

2 Likes

I’ve modified your code here.

local region = Region3.new(C1, C2) -- C1 and C2 are worldspace vectors
local regionMagnitude = C2 - C1
local materials, voxels = Terrain:ReadVoxels(region, 4)
local size = voxels.Size

-- Looping through the voxels
for x = 1, size.X, 1 do
    for y = 1, size.Y, 1 do
        for z = 1, size.Z, 1 do
            local material, voxel = materials[x][y][z], voxels[x][y][z]
            if material == Enum.Material.Water then
                print("Found Voxel")
                -- Issue: How do I get the position of the voxel
                                local ratio = Vector3.new(x,y,z)/size
                                local relativeToC1 = ratio*regionMagnitude
                                local worldPosition = C1 + relativeToC1
                return true
            end
        end
    end
end

What I’ve done is get the magnitude of length, width and height of the region with C2-C1.
Once the voxel is found I get the ratio of the voxel’s position relative to the region. With that ratio I multiply it by the region’s magnitude and add that onto C1 to get the worldspace position. Note that this will only work assuming that C1 is the bottom most and left most corner.

7 Likes