RobloxScripterAI
Discord ↗
Link Copied to Clipboard
×
"the npc should only be able to attack the door/player if it is within attack range (5)"
-- server script local pfs = game:GetService("PathfindingService") local dummy = script.Parent local waypoints = script.Parent.Parent.Parent.Waypoints:GetChildren() -- List of waypoints local door = game.Workspace.Door local aggroRange = 10 local doorRange = 30 local attackRange = 5 local isAttacking = false local currentWaypointIndex = 1 -- Function to attack a player local function attackPlayer(player) if isAttacking then return end -- if the NPC is already attacking, don't run the function again isAttacking = true dummy.Humanoid:MoveTo(player.Character.HumanoidRootPart.Position) while (player.Character.HumanoidRootPart.Position - dummy.HumanoidRootPart.Position).Magnitude > attackRange do wait(0.1) -- wait for a short time before checking the distance again end local attackAnimation = dummy.Humanoid:LoadAnimation(dummy.Animations.AttackAnimation) attackAnimation:Play() wait(2) -- attack cooldown attackAnimation:Stop() -- if the player is still within range, damage them if (player.Character.HumanoidRootPart.Position - dummy.HumanoidRootPart.Position).Magnitude < attackRange then player.Character.Humanoid:TakeDamage(10) print("NPC damaged the player!") -- log the damage event end isAttacking = false end -- Function to move to the next waypoint or door local function moveToNextWaypointOrDoor() if currentWaypointIndex <= #waypoints then local path = pfs:CreatePath() path:ComputeAsync(dummy.HumanoidRootPart.Position, waypoints[currentWaypointIndex].Position) for _, waypoint in pairs(path:GetWaypoints()) do dummy.Humanoid:MoveTo(waypoint.Position) dummy.Humanoid.MoveToFinished:Wait() end currentWaypointIndex = currentWaypointIndex 1 else dummy.Humanoid:MoveTo(door.Position) if (door.Position - dummy.HumanoidRootPart.Position).Magnitude < attackRange then local attackAnimation = dummy.Humanoid:LoadAnimation(dummy.Animations.AttackAnimation) attackAnimation:Play() print("NPC is attacking the door!") -- log the attack event end end end -- Check for players within aggro range while true do local playersInRange = false for _, player in pairs(game.Players:GetPlayers()) do if (player.Character.HumanoidRootPart.Position - dummy.HumanoidRootPart.Position).Magnitude < aggroRange then attackPlayer(player) playersInRange = true break end end if not playersInRange then moveToNextWaypointOrDoor() end wait(0.5) -- check every half second end -- Start the NPC's behavior spawn(moveToNextWaypointOrDoor)