Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Can't figure how to cast a ray to the player?

Hello, i am trying to create a ray that points towards the player and should go to him, but my script never works and it just prints that it never hit something and is nil. My ray may not be pointing at the player and somewhere else, i don't know. How do i fix this?

Script:

wait(1)

while true do
    wait()
    
    local target
    
    local mag = math.huge
    
    for i, v in pairs(game.Players:GetPlayers()) do
        local magnitude = (v.Character:WaitForChild("HumanoidRootPart").Position - script.Parent.Model.Union.Position).Magnitude
        
        if magnitude < mag then
            mag = magnitude
            
            target = v.Character
        end
    end
    
    if target ~= nil then
        local ray = Ray.new(script.Parent.Model.Union.Position, (script.Parent.Model.Union.Position - target.HumanoidRootPart.Position).Unit * 2000000000000000000000000000000000000000000000000000000000000)
        
        local hit, pos = workspace:FindPartOnRay(ray)
        
        if hit ~= nil then
            print(hit, pos)
            
            local length = (script.Parent.Model.Union - pos).Magnitude
            
            if length <= 40 then
                if hit.Parent == target then
                    local partSet = script.Parent.Model.Union
                    
                    partSet.CFrame = CFrame.new(partSet.Position, pos)
                    
                    target.Humanoid:TakeDamage(5)
                    
                    wait(0.01)
                else
                    local partSet = script.Parent.Model.Union
                    
                    partSet.CFrame = CFrame.new(partSet.Position, pos)
                end
            end
        else
            print("nil")
        end
    end
end

The important part is local ray = Ray.new(script.Parent.Model.Union.Position, (script.Parent.Model.Union.Position - target.HumanoidRootPart.Position).Unit

1 answer

(script.Parent.Model.Union.Position - target.HumanoidRootPart.Position)

Its the other way around, The target position should be first, then the origin

(target.HumanoidRootPart.Position - script.Parent.Model.Union.Position)

This discussion is preserved as it was. New answers, comments, and votes are closed.