Having trouble with RayCasting

I am a amateur scripter who is just starting with ray casting . I have managed to create a automatic turrent gun that shoots things in a specific radius , all the code is done except for the fact that it shoots through walls. I have been trying to find tutorials on youtube on how to do it but they all either are bad at explaining or are outdated. Can someone please tell me how to do this ?

If you right downa script for me to see use :
(local torso) as the target and ending point of the ray
(local barrel) as the Starting point of the bullet and starting point of the ray
(local distance) as the max range of the turrent

I’m going to guess that you haven’t seen the devhub resources for this since you said that you’ve only looked tutorials on youtube. Here’s the helpful startingp oint


To add to what you said, I think @Mioxity is looking for raycast filtering and should look into that for more detailed information, but that post has some info on it already.

Thanks I will read up on it. Also thanks for the site, should be useful.

Well all you would need to do is get the origin of the raycast (barrel)
then you would need to get the direction to the player

local Dist = (torso.Position - barrel.Position)

then you would need to make it a unit vector (basically make its distance 1)

local Unit = Dist.Unit

Now when you multiply Unit by your distance you will get the full direction

local FullDirection = Unit*distance

Now that you got your origin and your full direction you can raycast!

local RaycastResult = Workspace:Raycast(barrel.Position, FullDirection)

This works well, except for the fact that it hits the barrel of the gun
to fix that we can add an ignore list with raycast params

local Rayp = RaycastParams.new()
Rayp.FilterDescendantsInstances = {TurretInstance}

Now if we use Rayp in our Raycast it should filter out the turret instance

local RaycastResult = Workspace:Raycast(barrel.Position, FullDirection, Rayp)

from here its as simple as testing if we hit the player

if RaycastResult and
   RaycastResult.Instance and
   RaycastResult.Instance:IsDescendantOf(torso.Parent) then
      --do stuff here