HumanoidRootPart improperly positioning even though raycast intersection is correctly positioned

Hello, I’m trying to properly set a range to a keybind teleport where if your mouse is outside the maximum range, you would get teleported to the maximum range in the proper direction. Which works, however I added extra raycast checks to prevent teleporting inside of certain places and such. The problem, as seen below, risen after these checks were implemented.

Should be clear by itself but if not, here’s an explanation, firstly I get close to a wall or something ingame, then I press Z which is bound to inputbegan, remote fires, eventually getting to the module with the teleport code, then a ray fires towards the mouse position from the HumanoidRootPart’s position, then I’m supposed to get teleported to the ray intersection if there is any, however this is not the case, even though the intersection seems to be correctly placed, I just get teleported towards,0,0) for no apparent reason, either I’m missing something or just doing it plainly wrong, do not know, here’s the code:

    local vector3Value = plr.Stats.MousePosition.Value
    local y_Vector =,(rootPart.Size.Y * 0.5) + humanoid.HipHeight,0)
    local rayCastIgnoreTable = {workspace.Characters,workspace.Effects}
    if (rootPart.Position - vector3Value).Magnitude <= 50  then
        local ray =, vector3Value)
        local raycastHit, hitPosition = workspace:FindPartOnRayWithIgnoreList(ray, rayCastIgnoreTable)
        if raycastHit then
            local distance = (rootPart.Position - vector3Value).Magnitude
            local p ="Part")
            p.Anchored = true
            p.CanCollide = false
            p.Size =, 0.1, distance)
            p.CFrame = CFrame.lookAt(vector3Value, rootPart.Position)*, 0, -distance/2)
            p.Parent = workspace.Effects
            rootPart.Position = hitPosition + y_Vector
            rootPart.Position = vector3Value + y_Vector
        local lengthInSpace = (vector3Value - character.HumanoidRootPart.Position).Unit * 50
        local ray =, lengthInSpace)
        local hit, pos = workspace:FindPartOnRayWithIgnoreList(ray, rayCastIgnoreTable)
        if hit then
            rootPart.Position = pos + y_Vector
            rootPart.Position += lengthInSpace + y_Vector


The output in the video clearly prints only A meaning no external code was executed to interrupt the positioning. For the record, MousePosition value is being updated in a render-stepped loop from a client by invoking a remote function.
And yes I’m aware of the new raycasts, trust me I’ve tried both, this is the latest one I lost my hope on though. Any help is appreciated, thanks.