RayCasting not working right

I am making an enemy AI that will sneak on and chase a player in Roblox studio.
But while trying to use raycasting so the AI can check if a wall is in the way, I’ve had some problems
Here I raycast the AI’s rootpart.Position to it’s targets rootpart.Position
image
My code

local WallCheckParms = RaycastParams.new()
		WallCheckParms.FilterDescendantsInstances = {Character:GetDescendants(),Target.Parent:GetDescendants()}
		WallCheckParms.FilterType = Enum.RaycastFilterType.Blacklist
		local WallCheck = workspace:Raycast(HumRoot.Position,Target.Position,WallCheckParms)

I also have code that just puts a block at where the ray lands.

Why is my ray not going in the right direction, because of this my Ai doesn’t work right how do I fix this?

2 Likes

This has to do with how you’re handling your direction argument. Essentially, the direction argument expects a directional vector, not a positional vector.

Getting the direction is relatively easy, it’s just direction = goal - origin

So to plug it into your code,

local direction = Target.Position - HumRoot.Position
local WallCheck = workspace:Raycast(HumRoot.Position,direction,WallCheckParms)

Sorta off-topic but a little cool thing I wish I knew when I just started raycasting, you can also use this to determine the “seeing” distance,

local direction = Target.Position - HumRoot.Position
local unitVector = direction.Unit -- this essentially "limits" the "seeing" distance to 1 stud
-- now, let's say we wanted to limit the "seeing" distance to 100 studs,
local hundredStudsDirection = unitVector * 100
local WallCheck = workspace:Raycast(HumRoot.Position,hundredStudsDirection,WallCheckParms)
7 Likes

sadly, they don’t work like that;
it’s however rather simple to just fix your code:

local WallCheckParms = RaycastParams.new()
		WallCheckParms.FilterDescendantsInstances = {Character:GetDescendants(),Target.Parent:GetDescendants()}
		WallCheckParms.FilterType = Enum.RaycastFilterType.Blacklist
		local WallCheck = workspace:Raycast(HumRoot.Position,CFrame.new(HumRoot.Position,Target.Position).LookVector*100,WallCheckParms)

Basically, the raycast takes an initial position, and a direction (in this case the lookvector, for ease of understanding)

1 Like

That seems to fix it thanks for the help, Also thanks for the unit explanation since i never really knew how unit worked.

1 Like