I am making a butterfly that flyie around randomly. I'm wanting to make it so it doesn't fly through parts. Someone recommended using raycasting, however, by script isn't working.
The butterfly won't turn around when its gets near parts.
local R = Ray.new(Part.Position, Vector3.new(50,0,0))
local Butterfly = script.Parent.Parent -- The butterfly
local LWing = Butterfly.LWing -- The butterfly's wings
local RWing = Butterfly.RWing
local Body = script.Parent.Parent.PrimaryPart -- The primary part of the butterfly so I can use the CFrame
while true do
wait()
local PartFound, Pos = workspace:FindPartOnRayWithIgnoreList(R, { -- The ignore list is the butterflys body parts, I'm usnure how to shorten it but that doesn't have anything to do with my question
Butterfly.Torso1, Butterfly.ConfirmedButterfly,
Butterfly.Head, Butterfly.LeftAntenna,
Butterfly.RightAntenna, RWing.Center,
RWing.Hinge,
RWing.Part1, RWing.Part2,
RWing.Part3, RWing.Part4,
RWing.Part5, RWing.Part6,
RWing.Wedge1, RWing.Wedge2,
RWing.Wedge3, RWing.Wedge4,
LWing.Center, LWing.Hinge,
LWing.Part1, LWing.Part2,
LWing.Part3, LWing.Part4,
LWing.Part5, LWing.Part6,
LWing.Wedge1, LWing.Wedge2,
LWing.Wedge3, LWing.Wedge4})
script.Parent.Parent:SetPrimaryPartCFrame(Body.CFrame*CFrame.Angles(math.rad(math.random(-5,5)), math.rad(math.random(-5,5)), math.rad(math.random(-5,5))))
wait()
script.Parent.Parent:SetPrimaryPartCFrame(Body.CFrame*CFrame.new(1,0,0)) -- Makes the butterfly rotate in a random direction then go in that direction
if PartFound then -- Checks if a part was found by the Ray
if (PartFound.Position - Pos).Magnitude <= 5 then -- Checks the distance between the part and the butterfly
script.Parent.Parent:SetPrimaryPartCFrame(Body.CFrame*CFrame.Angles(math.rad(0), math.rad(180),math.rad(0))) -- Makes the butterfly turn around
script.Parent.Parent:SetPrimaryPartCFrame(Body.CFrame*CFrame.new(3,0,0)) -- Makes the butterfly move away
end
end
end
I don't understand why the butterfly isn't turning when it gets near parts. Any help would be appreciated. Thank you in advance.

2 comments
The butterfly still seems to fly through everything
Try reducing the distances by which it moves.