Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why is RayCasting not detecting humanoid most of the time?

Asked by 2 years ago

I have been trying to make a gun using raycasting, but most of the time when i click on a humanoid the ray goes past it and hits the baseplate (Evident using print functions to find out where the ray is hitting) Please help!

local Player = game.Players.LocalPlayer
local mouse = Player:GetMouse()
local mousepostion = mouse.hit.p
local tip = script.Parent:WaitForChild("Tip")
local waits = false
local event = script.Parent.GunInfo:WaitForChild("FireEvent")
local damage = 35
local range = 350
local ignore = {Player.Character, script.Parent}

local function click()
    if waits then return end
    waits = true
    local orgin = tip.Position
    local direction = (mousepostion - orgin).Unit * range
    local rayresult = Ray.new(orgin, direction)

    if rayresult then
        local part, position = workspace:FindPartOnRayWithIgnoreList(rayresult, ignore)
        local humanoid = part.Parent:FindFirstChild("Humanoid")
        if not humanoid then
            humanoid = part.Parent.Parent:FindFirstChild("Humanoid")
        end
        if humanoid then
            event:FireServer(humanoid, damage)
        else
        end
    end
    wait(.5)
    waits = false
end

script.Parent.Activated:Connect(click)

1 answer

Log in to vote
0
Answered by 2 years ago

mouseposition should be definied right before using it (probably the issue) server should decide damage instead of the client finding the humanoid should (probably) loop through the ancestors looking for a humanoid instead of just trying part.Parent and part.Parent.Parent

local par = part.Parent
local humanoid
local ran = 0
repeat
    humanoid = par:FindFirstChildOfClass("Humanoid")
    if humanoid then
        break
    end
    ran += 1
    par = part.Parent
until not par or ran >= 300

other than that the current code should work

Ad

Answer this question