Roblox Studio (LUA) - Enemy to orientation

465 Views Asked by At

I have NPC which, presumably, is an Enemy. I want it to return to OriginalPosition and OriginalOrientation after the player dies. However (as marked in a code-comment), with function :MoveTo(), the character doesn't return to the actual same position but an approximate. By example:

print(NPC.HumanoidRootPart.Position) -- Output: X: 11.5, Y: -2.13, Z: 15.49
print(OriginalPosition) -- Output: X: 11.4923973, Y: -2.13432, Z: 15.49

This is my code:

local FollowZone = script.Parent
local NPC = FollowZone.Parent

local OriginalOrientation = NPC.HumanoidRootPart.Orientation
local OriginalPosition = NPC.HumanoidRootPart.Position

print(OriginalPosition)
local Fighting = 2 -- 1; No Fighting. 2; Neutral. 3; Fighting

local function OnTouch(Part)
    if Part.Parent:FindFirstChild("Humanoid") ~= nil and tostring(Part.Parent.Parent.Name) ~= "Enemies" then
        local Target = game:GetService("Workspace"):WaitForChild(Part.Parent.Name)
        Fighting = 3

        while Fighting == 3 do
            NPC.Humanoid:MoveTo(Target.HumanoidRootPart.Position)
            
            if Target.Humanoid.Health == 0 then
                Fighting = 1
                BackToPosition()
                BackToOrientation()
            end
            
            wait()
        end
    end
end


function BackToPosition()
    while Fighting == 1 do
        NPC.Humanoid:MoveTo(OriginalPosition)
        
        print(NPC.HumanoidRootPart.Position) -- X: 11.5, Y: -2.13, Z: 15.49
        print(OriginalPosition) -- X: 11.4923973, Y: -2.13432, Z: 15.49 
        
        if NPC.HumanoidRootPart.Position == OriginalPosition then
            Fighting = 2
        end

        wait()
    end
end

function BackToOrientation()
    while NPC.HumanoidRootPart.Orientation ~= OriginalOrientation do
        for Index = 1, OriginalOrientation.X do
            NPC.HumanoidRootPart.Orientation = Vector3.new(Index, OriginalOrientation.Y, OriginalOrientation.Z)
        end
        
        wait()
    end
end


script.Parent.Touched:Connect(OnTouch)
1

There are 1 best solutions below

1
CozLex On
local FollowZone = script.Parent
local NPC = FollowZone.Parent

local OriginalPos = NPC.HumanoidRootPart.CFrame
local Fighting = 2 -- 1; No Fighting. 2; Neutral. 3; Fighting

local function OnTouch(Part)
    if Part.Parent:FindFirstChild("Humanoid") ~= nil and tostring(Part.Parent.Parent.Name) ~= "Enemies" then
        local Target = game:GetService("Workspace"):WaitForChild(Part.Parent.Name)
        Fighting = 3

        while Fighting == 3 do
            NPC.Humanoid:MoveTo(Target.HumanoidRootPart.Position)
            
            if Target.Humanoid.Health == 0 then
                Fighting = 1
                BackToOrginalPos()
            end
            
            wait()
        end
    end
end

function BackToOrginalPos()
    NPC.HumanoidRootPart.CFrame = OriginalPos
end


script.Parent.Touched:Connect(OnTouch)