Hello, I want to making enemy walk to part (Waypoint) in the game
but i have problem to used RunService.Heartbeat or something
function EnemyClass:MoveToWaypoints()
local EnemyStats = self.EnemyStats
local EnemyPart = self.EnemyPart
local EnemyCurrentWaypoint = self.EnemyCurrentWaypoint
local EnemyWaypoints = self.EnemyWaypoints
local function MoveToWaypoint(Waypoint: BasePart)
local MoveToFinished = false
local MoveToFinishedConnection = nil
MoveToFinishedConnection = RunService.Heartbeat:Connect(function(DeltaTime: number)
EnemyPart.CFrame = EnemyPart.CFrame * CFrame.new(0, 0, -1 * DeltaTime)
if EnemyPart.CFrame == Waypoint.CFrame then
MoveToFinishedConnection:Disconnect()
MoveToFinished = true
return
end
--EnemyRendererRemote:FireAllClients('UpdateEnemyPosition', EnemyPart.Position)
end)
end
for WaypointNumber = 1, #EnemyWaypoints do
EnemyCurrentWaypoint = WaypointNumber
local Waypoint = self:GetEnemyWaypointByNumber(EnemyCurrentWaypoint)
MoveToWaypoint(Waypoint)
end
end
I’ve been trying to calculate the distance of EnemyPart to the waypoint, but I can’t seem to get it.
function EnemyClass:MoveToWaypoints()
local EnemyStats = self.EnemyStats
local EnemyPart = self.EnemyPart
local EnemyWaypoints = self.EnemyWaypoints
local function MoveToWaypoint(Waypoint: BasePart)
return task.spawn(function()
local speed = EnemyStats.Speed
while true do
local direction = (Waypoint.Position - EnemyPart.Position).Unit
local distance = (Waypoint.Position - EnemyPart.Position).Magnitude
local deltaMovement = direction * speed * RunService.Heartbeat:Wait()
if distance <= deltaMovement.Magnitude then
EnemyPart.Position = Waypoint.Position
break
else
EnemyPart.Position += deltaMovement
end
end
end)
end
for _, Waypoint in ipairs(EnemyWaypoints) do
MoveToWaypoint(Waypoint)
task.wait()
end
end
function EnemyClass:MoveToWaypoints()
local EnemyStats = self.EnemyStats
local EnemyPart = self.EnemyPart
local EnemyCurrentWaypoint = self.EnemyCurrentWaypoint
local EnemyWaypoints = self.EnemyWaypoints
--local EnemyWalkSpeed = number -- Make EnemyWalkSpeed
local function MoveToWaypoint(Waypoint: BasePart)
--local EnemyWalkTime = 1/EnemyWalkSpeed * (Waypoint.Position - EnemyPart.Position).Magnitude + 0.225 -- Same with Humanoid WalkSpeed
local Tween = game.TweenService:Create(EnemyPart, TweenInfo.new(EnemyWalkTime), {Position = Waypoint.Position})
Tween:Play()
Tween.Completed:Wait()
--task.wait(0.25) -- Delay
end
for WaypointIndex = 1, #EnemyWaypoints do
EnemyCurrentWaypoint = WaypointIndex
local Waypoint = self:GetEnemyWaypointByNumber(EnemyCurrentWaypoint)
MoveToWaypoint(Waypoint)
end
end