Hello devs,I have been using raycast and this happened :
Code :
local TweenService = game:GetService("TweenService")
local NPC = script.Parent
local animation = NPC.NPC:LoadAnimation(NPC:WaitForChild("Animation"))
local function getPlayer(distance)
local player, dist = nil, distance
for _,plr in pairs(workspace:GetChildren()) do
if plr:FindFirstChild("Humanoid") then
if (script.Parent.HumanoidRootPart.Position - plr.HumanoidRootPart.Position).Magnitude < dist then
player = plr
end
end
end
return player, dist
end
spawn(function()
while wait(1) do
local player, dist = getPlayer(math.huge)
if player then
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {script.Parent}
rayParams.FilterType = Enum.RaycastFilterType.Blacklist
local rayResult = workspace:Raycast(script.Parent.Hat.Position, player.Head.Position, rayParams)
if rayResult then
local hitPart = rayResult.Instance
if hitPart then
print(hitPart.Name)
end
else
if player.Humanoid.Health > 0 then
local hat = script.Parent.Hat:Clone()
for _,i in pairs(hat:GetChildren()) do
if i:IsA("WeldConstraint") then
i:Destroy()
end
end
hat.Parent = workspace
hat.Anchored = true
hat.Transparency = 0
animation:Play()
script.Parent.Head.Toppat.Transparency = 1
local Go = TweenService:Create(hat, TweenInfo.new(0.5, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, 0), {
CFrame = player.Head.CFrame
})
Go:Play()
Go.Completed:Wait()
Go:Destroy()
local dist = (hat.Position - player.HumanoidRootPart.Position).Magnitude
if dist < 5 then
player.Humanoid:TakeDamage(10)
end
script.Parent.Head.Toppat.Transparency = 0
hat:Destroy()
else
script.Parent.Head.Toppat.Transparency = 0
for _,i in pairs(workspace:GetChildren()) do
if i:IsA("Part") or i:IsA("BasePart") or i:IsA("UnionOperation") then
if i.Name == "Hat" then
i:Destroy()
end
end
end
end
end
end
end
end)
spawn(function()
while wait() do
local player = getPlayer(math.huge)
if player then
script.Parent:SetPrimaryPartCFrame(CFrame.lookAt(script.Parent.HumanoidRootPart.Position, player.HumanoidRootPart.Position * Vector3.new(1, 0, 1) + script.Parent.HumanoidRootPart.Position * Vector3.new(0, 1, 0)))
end
end
end)
The Raycast basically sometimes work and sometimes not.
Thank you for help!