Ray not casting in the direction it should?

I’m working on some simple enemy AI, it’s a drone so I’m not using pathfinding. Instead when a player is detected inside of it’s range it casts a ray towards the player to confirm visibility and then attacks the player.

However, the ray seems to be casting in the right direction only half of the time as can be seen in this video. (The issue appears at about half of the video, the blue parts represent the position where the ray hit, they are added to the ignorelist to make sure the ray doesn’t hit them)
robloxapp-20200526-0008434.wmv (4.9 MB)

Raycasting has been my downfall for a while already and here I am completely confused again so I thought I’d ask for some help.

--raycast towards the player to check visibility
--closest part is the closest humanoidrootpart present in the region
local checkRay = Ray.new(closestPart.Position, (drone.Position - closestPart.Position).unit * range)
local checkPart, checkPosition = workspace:FindPartOnRayWithIgnoreList(checkRay, ignorelist, false, true)
1 Like

To me it looks like the ray is drawn correctly.
It is however drawn from the player toward the drone not the other way around.

It looks like the error lies either within the drawing of the cube. Or the defining of closestPart. If you post the rest of the code regarding these it will help us find the error.

1 Like

Oh! That actually makes sense as to why the ray could go the other direction. I am still confused as to how it would output me HumanoidRootPart as the part it hit if it’s facing towards the drone?

I am 100% positive the cube drawing is good, since I am also printing the checkPart and it’s nil when it misses. I’ll change the code in a bit and update you if the problem is fixed!

1 Like

Yep the ray was reversed, got it fixed now! Thank you

2 Likes