Hello working on a tower defense game and I finished with my enemy code, but it’s pretty scuffed so looking to get help with improving it mostly just the movement part since it’s a bit wack.
For the movement, I decided to not manually set up nodes for maps since I was lazy and felt like it would be better anyways to make it so it automatically makes the nodes so all I need to do is make a map and then it just works, but I don’t think my math for this is good and I also don’t know if MoveTo is the best choice since it doesn’t seem to be accurate the enemies don’t walk all the way to the node.
function Enemy.new(model,speed,damage)
local self = {}
local lastPos = nil
--warn("Creating Enemy")
self.model = model:Clone()
self.Humanoid = self.model.Humanoid
self.HumanoidRootPart = self.model.HumanoidRootPart
self.damage = damage
self.model.HumanoidRootPart.CFrame = map.Start.CFrame
self.model.Parent = workspace.Game.Enemies
self.Humanoid.WalkSpeed = speed
PhysicModule:setNPCGroup(self.model)
--warn("Created Enemy")
--movement
--uses math because I was to lazy to setup nodes manually
for i = 1,#paths:GetChildren() do
local position = (paths[i].CFrame * CFrame.new(-(paths[i].Size.X/2)+offset,0,0)).p --default position
--because my math sucks (the position variable) doing this which just sets the position to the other end of the path
--(so I don't have to manually rotate the path)
--only downside is I can't have short paths (I don't th
if lastPos then
local distance = (lastPos-position).Magnitude
if distance < 5 then
position = (paths[i].CFrame * CFrame.new((paths[i].Size.X/2)-offset,0,0)).p --set the position to the otherside of the path
end
end
--if the path is roated then it's probably a ramp so
--set the node to the next paths start side so that the enemies can go all the way up the ramp
if (paths[i].Orientation == Vector3.new(0,0,-15)) or (paths[i].Orientation == Vector3.new(0,0,15)) then
position = (paths[i+1].CFrame * CFrame.new((paths[i+1].Size.X/2)-offset,0,0)).p
end
lastPos = position
--visualize node (debug)
--local part = Instance.new("Part")
--part.Size = Vector3.new(0.5,0.5,0.5)
--part.Parent = workspace
--part.CanCollide = false
--part.Anchored = true
--part.Position = position + Vector3.new(0,paths[i].Size.Y/2 + part.Size.Y/2)
--finally move the enemy
self.Humanoid:MoveTo(position)
self.Humanoid.MoveToFinished:Wait()
end
--reached the end so do damage and stuff
local GameManagerModule = require(SSS.Server.GameManager)
local gameInstance = GameManagerModule:GetGame()
gameInstance:TakeDamage(self.damage) --deal damage to the tower
self.model:Destroy()
gameInstance.enemiesLeft -= 1
return setmetatable(self,Enemy)
end