Raycasting not working

Hello everyone, I hope you’re having a good day. So I was just doing a project(that I most likely won’t finish) when I encountered a problem, the raycasting wasn’t working. There aren’t any errors in the output tab. Here’s the code :

--Raycasting
local params = RaycastParams.new()
params.IgnoreWater = true
params.FilterType = Enum.RaycastFilterType.Exclude
params:AddToFilter(target)
params:AddToFilter(char)
print(target.Position + Vector3.new(0, target.Size.Y/2 + 3, 0))
local raycast = game.Workspace:Raycast(target.Position, (target.Position + Vector3.new(0, target.Size.Y/2 + 3, 0)) - target.Position, params)
print(raycast)
if raycast then
	print("H")
	force.Position = target.Position + Vector3.new(0, (raycast.Position.Y - target.Position.Y)/2, 0)
else
	print("NH")
	force.Position = target.Position + Vector3.new(0, target.Size.Y/2 + 3, 0)
end

The target is the part that the mouse is pointing to. The raycast keeps showing up as nil. Any help would be appreciated.

The line where the raycast is made is the problem I think, especially this part

I would change it to something like this

Vector3.new(0, target.Size.Y/2 + 3, 0)) * RAYCAST_LENGHT--you must multiply it by the lenght you desire, if this is the direction of the raycast

If the Raycast returns nil, it didn’t hit anything. Currently, the code sends a Raycast from the part and 3 studs above it. It will only return a RaycastResult if there’s a part straight above. To fix this, you can increase the distance of the ray cast like this:

local raycast = game.Workspace:Raycast(target.Position, (target.Position + Vector3.new(0, target.Size.Y/2 + 3, 0)) * RAYCAST_DISTANCE - target.Position, params)

However, I’m unsure as to what you’re trying to do, so this could be wrong :smiley:

try multiplying the direction by 100 or another value as then it will go further and possibly hit a part as currently it’s going 3 studs then stopping

1 Like

I’m trying to detect whether there’s a part the three studs + half the targets height in order to respond to it accordingly @hya123456h @JOSIMA33

1 Like

so if I want it to be 3 studs, I multiply by 3?

My mistake, it turns out that it was all working, just that the part I was testing it on was exactly the height above the ray, but thanks for all the help, I appreciate it. I would mark them all as solutions but I can’t. @hya123456h @JOSIMA33 @nontoxicguy1

2 Likes