Raycast projectile has offset when target is mouse position

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UIS = game:GetService("UserInputService")
local Root = script.Parent:WaitForChild("HumanoidRootPart")

UIS.InputBegan:Connect(function(input, gameProcessedEvent)
    if gameProcessedEvent then return end

    if input.UserInputType == Enum.UserInputType.MouseButton1 then
        local unitRay = workspace.CurrentCamera:ViewportPointToRay(input.Position.X, input.Position.Y)
        local origin = Root.Position
        local direction = unitRay.Direction * 3

        local raycastParams = RaycastParams.new()
        raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
        raycastParams.FilterDescendantsInstances = {script.Parent}
        local p2 = ReplicatedStorage.Part:Clone()
        p2.Parent = workspace.Ignore
        p2.Size = Vector3.new(0.2,0.2,1)
        p2.Color = Color3.fromRGB(205, 180, 0)
        for _ = 1, 100 do
            local result = workspace:Raycast(origin, direction, raycastParams)
            if result then
                if result.Instance.Parent ~= workspace.Ignore then
                    p2.Position = result.Position
                    break
                end
            end
            p2.CFrame = CFrame.lookAt(origin + direction, origin) * CFrame.new(0, 0, -direction.Magnitude / 2)
            origin += direction
            direction += Vector3.new(0, -0.01, 0)
            task.wait()
        end
        task.delay(0.5, function()
            p2:Destroy()
        end)
    end
end)

Produces these results: https://gyazo.com/225e2d52848bb4a4a77cb0e0b51f9804

Why is there such an offset when presumably ViewportPointToRay ignores any GUI offset?

P.S. I don’t want to use the Mouse object if possible.

Try ScreenPointToRay? I think you want to include the offset.

Tried it, same kind of result unfortunately.
https://gyazo.com/3c4a923f292effb207b67fc0b71ed918

Just do Mouse Hit Position - origin.

1 Like

I’d like to avoid using the Mouse object if possible.

You’re still using the mouse either way, so just use the Mouse hit.

Also if you really want the mouse position you need to do this;

local mousePos = uis:GetMouseLocation() - Vector2.new(0, game:GetService("GuiService"):GetGuiInset().Y)

That’s not the problem here. The problem is that when I include Root.Position as the origin, there’s an offset from that. If I raycast directly from camera to mouse, it works fine but looks like this:
https://gyazo.com/037c674a3238b90b436964cf5035a689

It’s offset because the projectile is being casted from the root position and hence the path is not the same as the unit ray which has its own seperate .Position starting point.

To get the proper direction you will need to do like @varjoyTes said.

Here is the mouse alternative.

3 Likes