I am creating a tower defense and I have multiple towers that I am trying to figure out how to rotate toward the nearest mob walking by.
This is my current script; The tower rotation will take place within 'While true do'
:
Summary
local TweenService = game:GetService("TweenService")
local tower = script.Parent.Position
local mobs = workspace.MobRealm
local function FindNearestTarget()
local maxRange = 35
local nearestTarget = nil
for i, target in ipairs(mobs:GetChildren()) do
local distance = (target.HumanoidRootPart.Position - tower.Position).Magnitude
if distance < maxRange then
nearestTarget = target
maxRange = distance
end
end
return nearestTarget
end
while true do
local target = FindNearestTarget()
if target then
local x = target.HumanoidRootPart.CFrame.X
local y = target.HumanoidRootPart.CFrame.Y
local z = target.HumanoidRootPart.CFrame.Z
print(x, y, z)
x = math.deg(x)
y = math.round(math.deg(y) / 90) * 90
z = math.deg(z)
print(x, y, z)
local half = math.pi / 2
y = math.round(y / half ) * half
local goal = tower.Parent.PrimaryPart.CFrame * CFrame.Angles(x,y,z)
print(goal)
tower.Parent.PrimaryPart:PivotTo(goal)
print("Complete")
end
task.wait(.1)
end
As you can see all prints
are working.
The tower does not rotate at all, and there are no errors in Output
, I just cannot figure out how to get it working.