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

How do I make the NPC not unnecessarily turn a full 360?

Asked by 5 years ago

Here I've made a script stored in the ServerScriptService where the AI would turn around and face towards the targeted brick

local dude = workspace.Noob

local faceTarget = function(target)
    local settings = {
        horizontalRange = math.rad(math.huge);
        verticalRange = math.rad(math.huge);
        maxHorizontalWaist = math.rad(math.huge);
    }

    local hrp = dude:WaitForChild("HumanoidRootPart");
    local torsojoint = hrp:WaitForChild("Root Hip");
    local tjC0 = torsojoint.C0;

    local springPart = dude:WaitForChild("Spring");
    local BP = springPart:WaitForChild("BodyPosition");

    BP.Position = Vector3.new();
    springPart.CFrame = CFrame.new();
    springPart.Anchored = false;

    local lookAt = function(thing)
        local eye = (hrp.CFrame * CFrame.new(0, 0, 0)):pointToObjectSpace(thing).Unit;
        local horizontal = -math.atan2(eye.x, -eye.z);
        local vertical = math.asin(eye.y);

        local goal = Vector3.new();
        if not (math.abs(horizontal) > settings.horizontalRange or math.abs(vertical) > settings.verticalRange) then
            local hsign, habs = math.sign(horizontal), math.abs(horizontal);
            local hwaist = habs*1.1;

            if (hwaist > settings.maxHorizontalWaist) then
                local remainder = hwaist - settings.maxHorizontalWaist;
                hwaist = settings.maxHorizontalWaist;
            end
            goal = Vector3.new(hsign, hsign*hwaist, vertical);
        end
        return goal;
    end
    game:GetService("RunService").Heartbeat:Connect(function(dt)
        BP.Position = lookAt(target.Position);
        local set = springPart.Position;
        torsojoint.C0 = tjC0 * CFrame.fromEulerAnglesYXZ(0, 0, set.y);
    end);
end

faceTarget(workspace.Target)

Here's the issue: https://www.youtube.com/watch?v=zayt7CXnHT0&feature=youtu.be

The noob keeps unnecessarily turning a full 360 when the brick is the opposite of the Noob's original direction (The rotation before I started to go Run mode)

Answer this question