How to know if part is touching terrain

How can i know if a part is touching the grass material of my terrain

1 Like

May I ask in which case you plan to use this? For instance with a projectile the best methods of this could change, etc.

I am using brush tool to place down cactus and some of them are place on the wrong terrain and I just want to make a console code to remove the ones on the grass terrain

1 Like

Well in that case, lets wait for someone whos knows what they are doing to come to this post

1 Like

I made this but ists super inaccurate

local workspace = game:GetService("Workspace")

local function isTouchingGrass(part)
	local regionSize = Vector3.new(4, 4, 4) -- Small region around each part
	local partPosition = part.Position
	local region = Region3.new(partPosition - regionSize/2, partPosition + regionSize/2):ExpandToGrid(4)

	local material, _ = workspace.Terrain:ReadVoxels(region, 4)
	local size = material.Size

	for x = 1, size.X do
		for y = 1, size.Y do
			for z = 1, size.Z do
				print( material[x][y][z])
				if material[x][y][z] == Enum.Material.Grass then
					return true
				end
			end
		end
	end

	return false
end

for _, instance in pairs(workspace:GetDescendants()) do
	if instance:IsA("Part") and isTouchingGrass(instance) then
		
		script.Highlight:Clone().Parent = instance
	end
end

Usually, raycasting is your best bet.
Also always make sure to search up your posts’ topic, because chances are it’s already been answered.

You can do something like this:

local params = RaycastParams.new()
params.FilterDescendantsInstances = {workspace.Terrain}
params.FilterType = Enum.RaycastFilterType.Include

local ray = workspace:Raycast(script.Parent.Position, Vector3.new(0,-10,0) * 10, params) -- assuming script.Parent is a part
print(ray.Material) -- Enum.Material.Grass


Should work.

Hope this helps!

1 Like

Also sorry to bump, but you should probably consider the limitations of the Highlight Instance (which is apparently limited to 31 Instances, enabled or not).
Maybe your code works flawlessly but that’s creating a bottleneck!

1 Like

Thank you, i was just using it to visualize

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.