# Raycasting distance is not working as expected

Hello everyone,

Recently I have been working on a Shotgun. So basically it creates a ray inside a for loop because a Shotgun shoots multiple bullets.

I created the Shotgun Pattern by a random number between `-radius.Value` and `radius.Value`. Which `radius` can control the spread of it. Suppose itâs value is 8 here.

``````for i = 1,15 do
local ray = Ray.new(Shotgun.ShootPart.CFrame.p , (mouse.Hit.p - char.Shotgun.ShootPart.CFrame.p).unit*50 + Vector3.new(random1,random2, Shotgun.Radius.Value))
...
``````

And the Raycast will ignore the bullet itself:

``````local hit,pos = workspace:FindPartOnRay(ray, BulletTrail)
``````

And it will find the distance:

`````` local distance = (char.Shotgun.ShootPart.CFrame.Position - pos).magnitude
BulletTrail.Size = Vector3.new(0.05,0.05,distance)
BulletTrail.CFrame = CFrame.new(char.Shotgun.ShootPart.CFrame.p, pos) *
CFrame.new(0,0,-distance/2)
``````

So this should be an expected result:

You can see the bullets are spreaded clearly, going on itâs own way.
However, sometimes the distance returns to 0.01, shown below:

In this image you can clearly see thereâs only one bullet trail, other than that they wonât âexpandâ

Iâm sure thereâs no invisible walls blocking the ray, Iâm not sure is my `FindFirstOnRay` went wrong, or any algorithm is incorrect here, please let me know if you have any ideas or if you are confused, Thanks!!

1 Like

You should use FindPartOnRayWithIgnoreList to prevent the bullets you fired previously interfering with your raycast. On top of this, ensure your character is part of the IgnoreList table aswell so it too doesnât interfere when you shoot, this should fix the problem.

3 Likes

Do I do something like this? I donât know did I do it wrong:

``````local ignore = {}
table.insert(ignore,BulletTrail)
local hit,pos = workspace:FindPartOnRayWithIgnoreList(ray, ignore)``````

Yes that seems like it would work. Although I would define the ignore table outside of your FireBullet function (if you havenât already) so that you can add other objects to it like your character, otherwise it would be reset every time.

Note: This is definitely not necessary, but another thing you can do if youâre feeling a bit brave is use CollectionService to add the tag âIgnoreâ to objects which you are ignoring (e.g your bullet and character) and then use GetTagged(TagName) as your âIgnoreListâ, because it returns a table of instances with the âIgnoreâ tab:

``````CollectionService:AddTag(Bullet, "Ignore")
local Ignored = CollectionService:GetTagged("Ignore")
local hit,pos = workspace:FindPartOnRayWithIgnoreList(ray, Ignored)
``````

The benefit here is you donât need to insert things to a local table (you can add the Ignore tag to things from another script and fetch the table anywhere using CollectionService).

Thank you soooo much!! It looks way more satisfying!!

2 Likes