Raycasting distance is not working as expected

Hello everyone, :smile:

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!! :pray:

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!! :+1: It looks way more satisfying!! :smiley:

2 Likes