Raycasting not hitting when it starts inside a part (or maybe another issue)

Hello! I’m here because of a confusing issue I’m encountering.

When a raycast starts inside a part, it doesn’t seem to hit; it seems like it goes through the part and only stops when it hits the next part.

This is an issue because it impacts my building system and would improperly place buildings inside blocks.

See this diagram:

(Blue: Parts, Black: Player, Red: Raycast, Yellow: What the raycast is relative to, Green: Final chosen position)

In-Game Version

(The little green sliver is the chosen placement, wedged between two parts)

The code for raycasting (SnapToGround)

-- ModuleScript: game.ReplicatedStorage.Modules.Building

-- ...
module.UpLimit = 4
module.DownLimit = 8

local stgRCParams = RaycastParams.new()
stgRCParams.FilterType = Enum.RaycastFilterType.Blacklist
stgRCParams.IgnoreWater = false

function module:SnapToGround(pos, filter)
	stgRCParams.FilterDescendantsInstances = filter
	local origin = Vector3.new(pos.X, pos.Y + module.UpLimit, pos.Z)
	local result = workspace:Raycast(origin, Vector3.new(0, -module.UpLimit - module.DownLimit, 0), stgRCParams)
	if not result then return false end
	if result.Distance == 0 then return false end
	local posY = result.Position.Y
	return Vector3.new(pos.X, posY, pos.Z)

-- ...

UpLimit is how far up from the player’s feet that the raycast starts, and DownLimit is how far it goes down from there.

This is the code that calls it:

-- LocalScript directly inside PlayerGui
local rs = game:GetService("RunService")
local plr = game.Players.LocalPlayer

local buildModule = require(game.ReplicatedStorage.Modules.Building)
local snapPart = game.Workspace.snap

local chr = plr.Character
if not chr then
	chr = plr.CharacterAdded:Wait()

	local bpos = buildModule:GetPlayerBuildPos(plr) -- gets the spot in front of the player, nothing (?) wrong here
	local pos = buildModule:Snap(bpos) -- Snaps it to a grid of 2,2; offset by 1 (studs)
	local fpos = buildModule:SnapToGround(pos, { snapPart }) -- THIS IS THE PROBLEM!
	if not fpos then
		snapPart.BrickColor = BrickColor.new("Really red")
		snapPart.Position = pos
		snapPart.BrickColor = BrickColor.new("Parsley green")
		snapPart.Position = fpos

I really don’t know what’s the issue here; any sort of help or pointers would be appreciated!

You will have to return false in your SnapToGround function if there are any parts touching the starting point of the raycast.

To do this, since getting all parts touching a point doesn’t exist in roblox, I would recommend getting all parts touching a sphere with a small radius instead.

See this thread: Introducing OverlapParams - New Spatial Query API (especially the :GetPartBoundsInRadius() part)

1 Like

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