Need help with bone movements depending on terrain normal

So what I’m trying to do is, I currently have a character which is a skinned mesh and has 4 main legs which are being controlled by bones I want to move. These need to move in Z axis depending on how high or low the nearest ground is. So these legs will touch the ground even if ground is not flat. Here is what I’ve done so far:

Problem is, when these legs collide with a part of terrain, they basically go crazy. Also I have a print here just in case if it can’t find terrain, for some reasons it usually prints that when it’s not on a flat surface. Here is my code:

local char = script.Parent

local bones = {
    ["FR"] = char.gonarch_reference.Leg_FR_1;
    ["FL"] = char.gonarch_reference.Leg_FL_1;
    ["BR"] = char.gonarch_reference.Leg_BR_1;
    ["BL"] = char.gonarch_reference.Leg_BL_1

local raycastParams =
raycastParams.IgnoreWater = false
raycastParams.FilterDescendantsInstances = {script.Parent}
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

local function raycast(partToRaycast)
    local raycastResult = workspace:Raycast(partToRaycast.Position, -partToRaycast.CFrame.UpVector * 4, raycastParams)
    local boneName = string.split(partToRaycast.Name, "_")[1]
    local bone = bones[boneName]
    if raycastResult then
        print(partToRaycast.Name, raycastResult.Normal)            
        if boneName == "FR" then
            bone.Orientation =, -135, 21.978 * (1 - math.abs(raycastResult.Normal.Z)))
        elseif boneName == "FL" then
            bone.Orientation =, -45, 21.978 * (1 - math.abs(raycastResult.Normal.Z)))
        elseif boneName == "BR" then
            bone.Orientation =, 135, 21.978 * (1 - math.abs(raycastResult.Normal.Z)))
        elseif boneName == "BL" then
            bone.Orientation =, 45, 21.978 * (1 - math.abs(raycastResult.Normal.Z)))
        print("no result")

while true do
    for _, v in pairs(char.RaycastParts:GetChildren()) do

This is a server script inside the character. My raycast parts are welded with a weld constraint to the lowest part of the leg. As far as I can see, these don’t detact while character is moving so it’s probably not the problem.
Also please ignore the code being not professional, this is just in a quick testing stage and will be optimized later.

I would appreciate any helpful tips since I’m just stuck right now.