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

Unable to cast double to Vector3?

Asked by 1 year ago
Edited 1 year ago

Im trying to learn raycast functions for a practice gun model but I keep recieving the error, any ideas on how to fix it, heres my code:

local mouse = game.Players.LocalPlayer:GetMouse()
local handle = script.Parent

function shootRay()
    local startPos = handle.Parent.PrimaryPart.Position
    local endPos = startPos + handle.Parent.PrimaryPart.CFrame:vectorToObjectSpace(Vector3.new(1, 0, 0))
    local ray = Ray.new(startPos, endPos)
    local result = game.Workspace:Raycast(ray, 100)  --Line receiving the Error

    if result.Hit then
        local humanoid = result.Hit:FindFirstChild("Humanoid")
        if humanoid then
            humanoid:TakeDamage(10)
        end
    end
end

mouse.Button1Down:Connect(function(plr)
    shootRay()
end)

P.S. Im just getting back into scripting after a long time, so please bear with me

1 answer

Log in to vote
0
Answered by 1 year ago

Did you meant to use Workspace:FindPartOnRay()? Because Rays only work for Workspace:FindPartOnRay() and not Workspace:Raycast().

Also, Workspace:FindPartOnRay() and Ray are deprecated and should use Workspace:Raycast() instead, along with RaycastParams.

To do the Workspace:Raycast(), you don't need to make a Ray for it. Instead, put the origin and the direction as the arguments, and an optional RaycastParams as the third argument.

However, this won't return a Tuple (hit, pos, etc.) like what Workspace:FindPartOnRay() does. Instead, this will return a RaycastResult. This contains an Instance (or the hit in Workspace:FindPartOnRay()), a Position (or the pos in Workspace:FindPartOnRay()), and many more.

local mouse = game.Players.LocalPlayer:GetMouse()
local handle = script.Parent

function shootRay()
    local startPos = handle.Parent.PrimaryPart.Position
    local endPos = startPos + handle.Parent.PrimaryPart:GetPivot():VectorToObjectSpace(Vector3.new(1, 0, 0))
    local result = game.Workspace:Raycast(startPos, endPos * 100)

    if result.Instance then
        local humanoid = result.Instance.Parent:FindFirstChildWhichIsA("Humanoid")
        if humanoid then
            humanoid:TakeDamage(10)
        end
    end
end

mouse.Button1Down:Connect(shootRay)
Ad

Answer this question