give it a gun
local tool = script.Parent
local gunEvent = tool:WaitForChild("GunEvent")
local RunService = game:GetService("RunService")
local Handle = tool:WaitForChild("Handle")
local Reload = Handle:WaitForChild("Reload")
local Shoot = Handle:WaitForChild("Shoot")
local Empty = Handle:WaitForChild("Empty")
local muzzle = tool:WaitForChild("Muzzle")
local BULLET_SPEED = 100
local BULLET_LIFETIME = 5
local DAMAGE_BODY = 15
local DAMAGE_HEAD = 30
local COOLDOWN = 60 / 600
local RELOAD_TIME = 2.647
local defaultGrip = {
Right = Vector3.new(0.040, 0.017, -0.999),
Up = Vector3.new(-0.838, 0.544, -0.024),
Forward = Vector3.new(-0.543, -0.838, -0.036),
Pos = Vector3.new(0.248, -0.187, 0.009)
}
local reloadGrip = {
Right = Vector3.new(0.040, 0.017, -0.999),
Up = Vector3.new(-0.508, 0.861, -0.005),
Forward = Vector3.new(-0.860, -0.508, -0.043),
Pos = Vector3.new(0.101, -0.136, 0.004)
}
local function fromGripTable(grip)
return CFrame.fromMatrix(grip.Pos, grip.Right, grip.Up)
end
local playerStates = {}
local function getState(player)
playerStates[player] = playerStates[player] or {
lastShot = 0,
isReloading = false,
}
return playerStates[player]
end
local function addTrail(bullet)
local att0 = Instance.new("Attachment", bullet)
att0.Position = Vector3.new(0, 0, -bullet.Size.Z / 2)
local att1 = Instance.new("Attachment", bullet)
att1.Position = Vector3.new(0, 0, bullet.Size.Z / 2)
local function tweenGrip(fromGrip, toGrip, duration)
local startTime = tick()
while tick() - startTime < duration do
if not tool:IsDescendantOf(game) then break end
local alpha = (tick() - startTime) / duration
tool.Grip = fromGrip:Lerp(toGrip, alpha)
RunService.Heartbeat:Wait()
end
if tool:IsDescendantOf(game) then
tool.Grip = toGrip
end
end
local function createBullet()
local bullet = Instance.new("Part")
bullet.Size = Vector3.new(0.108, 0.118, 0.214)
bullet.Color = Color3.fromRGB(248, 217, 109)
bullet.Material = Enum.Material.DiamondPlate
bullet.Anchored = true
bullet.CanCollide = false
bullet.CFrame = muzzle.CFrame
bullet.Name = tostring(math.random() * 100)
bullet.Parent = workspace
return bullet
end
local function shootBullet(originCFrame, direction, character)
local bullet = createBullet()
bullet.CFrame = CFrame.new(originCFrame.Position, originCFrame.Position + direction)
code
local startTime = tick()
local lastPos = originCFrame.Position
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {character, tool}
rayParams.FilterType = Enum.RaycastFilterType.Exclude
local conn
conn = RunService.Heartbeat:Connect(function()
local elapsed = tick() - startTime
if elapsed > BULLET_LIFETIME then
bullet:Destroy()
conn:Disconnect()
return
end
local newPos = originCFrame.Position + direction.Unit * BULLET_SPEED * elapsed
local rayResult = workspace:Raycast(lastPos, newPos - lastPos, rayParams)
if rayResult then
local hit = rayResult.Instance
local target = hit:FindFirstAncestorOfClass("Model")
local hum = target and target:FindFirstChild("Humanoid")
if hum then
if hit.Name == "Head" then
hum:TakeDamage(DAMAGE_HEAD)
else
hum:TakeDamage(DAMAGE_BODY)
end
end
bullet:Destroy()
conn:Disconnect()
else
bullet.CFrame = CFrame.new(newPos, newPos + direction)
lastPos = newPos
end
end)
end
local function resetGrip()
tool.Grip = fromGripTable(defaultGrip)
end
tool.AncestryChanged:Connect(function(_, parent)
if not parent or not parent:IsDescendantOf(game.Players) then
Handle.CanTouch = false
if tool:FindFirstChild("Barrel") then tool.Barrel.CanTouch = false end
if tool:FindFirstChild("Mag") then tool.Mag.CanTouch = false end
task.delay(1.5, function()
Handle.CanTouch = true
if tool:FindFirstChild("Barrel") then tool.Barrel.CanTouch = true end
if tool:FindFirstChild("Mag") then tool.Mag.CanTouch = true end
end)
end
end)
gunEvent.OnServerEvent:Connect(function(player, action, ...)
local character = player.Character
if not character then return end
code
local state = getState(player)
local ammo = tool:FindFirstChild("Ammo")
local maxAmmo = tool:FindFirstChild("MaxAmmo")
if not ammo or not maxAmmo then return end
if action == "shoot" then
local origin, direction = ...
if typeof(origin) ~= "Vector3" or typeof(direction) ~= "Vector3" then return end
if state.isReloading or tick() - state.lastShot < COOLDOWN then return end
if ammo.Value <= 0 then
Empty:Play()
end
if ammo.Value > 0 then
state.lastShot = tick()
ammo.Value -= 1
Shoot:Play()
shootBullet(muzzle.CFrame, direction, character)
end
elseif action == "reload" then
if ammo.Value >= maxAmmo.Value or state.isReloading then return end
state.isReloading = true
tool.CanBeDropped = false
tool.Enabled = false
Reload:Play()
task.spawn(function()
tweenGrip(fromGripTable(defaultGrip), fromGripTable(reloadGrip), 0.25)
end)
task.delay(RELOAD_TIME, function()
if ammo and maxAmmo then ammo.Value = maxAmmo.Value end
task.spawn(function()
tweenGrip(fromGripTable(reloadGrip), fromGripTable(defaultGrip), 0.25)
end)
tool.CanBeDropped = true
tool.Enabled = true
state.isReloading = false
end)
end
end)
use the gun script from here
Assistant
Okay, here's the combined script, integrating the NPC following behavior with the gun functionality. I've made adjustments to ensure the NPC can equip and use the gun, and to handle the gun's events.
lua
-- NPC Script (Combined Following and Gun)
local NPC = script.Parent -- Assuming the script is inside the NPC model
local Humanoid = NPC:WaitForChild("Humanoid")
local RootPart = NPC:WaitForChild("HumanoidRootPart")
local Gun = NPC:WaitForChild("Gun") -- Assuming the gun is a child of the NPC
-- Configuration
local FOLLOW_RANGE = 50 -- Distance in studs
local STOP_DISTANCE = 5 -- Stop following when this close to the player
local CHECK_INTERVAL = 0.5 -- How often to check for players (in seconds)
local DAMAGE_AMOUNT = 5 -- Damage dealt on touch
local TOUCH_DAMAGE_COOLDOWN = 2 -- Cooldown for damage on touch (seconds)
local SPECIAL_ATTACK_CHANCE = 0.2 -- 20% chance for special attack
local SPECIAL_ATTACK_DAMAGE = 15 -- Damage dealt during special attack
-- Light Tweening (for special attack)
local Light = NPC:WaitForChild("Head"):WaitForChild("Light") -- Assuming the "Light" part is inside the NPC's Head
local TweenService = game:GetService("TweenService")
local LIGHT_TWEEN_IN_INFO = TweenInfo.new(1, Enum.EasingStyle.Linear) -- Slow fade-in
local LIGHT_TWEEN_OUT_INFO = TweenInfo.new(0.5, Enum.EasingStyle.Linear) -- Fast fade-out
-- Function to find the nearest player within range
local function findNearestPlayer()
local nearestPlayer = nil
local shortestDistance = FOLLOW_RANGE
for _, player in pairs(game.Players:GetPlayers()) do
if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
local distance = (player.Character.HumanoidRootPart.Position - RootPart.Position).Magnitude
if distance < shortestDistance then
nearestPlayer = player
shortestDistance = distance
end
end
end
return nearestPlayer, shortestDistance
end
-- Function to deal damage to a player
local function dealDamage(player, damageAmount)
if player and player.Character and player.Character:FindFirstChild("Humanoid") then
local humanoid = player.Character.Humanoid
humanoid:TakeDamage(damageAmount)
end
end
-- Function to perform a special attack
local function performSpecialAttack(targetPlayer)
-- Fade in the light
local fadeInTween = TweenService:Create(Light, LIGHT_TWEEN_IN_INFO, { Transparency = 0 })
fadeInTween:Play()
wait(LIGHT_TWEEN_IN_INFO.Time) -- Wait for the light to fully fade in
-- Deal special attack damage
dealDamage(targetPlayer, SPECIAL_ATTACK_DAMAGE)
-- Fade out the light
local fadeOutTween = TweenService:Create(Light, LIGHT_TWEEN_OUT_INFO, { Transparency = 1 })
fadeOutTween:Play()
end
-- Gun Functions (from your provided script)
local BULLET_SPEED = 100
local BULLET_LIFETIME = 5
local DAMAGE_BODY = 15
local DAMAGE_HEAD = 30
local COOLDOWN = 60 / 600
local RELOAD_TIME = 2.647
local defaultGrip = {
Right = Vector3.new(0.040, 0.017, -0.999),
Up = Vector3.new(-0.838, 0.544, -0.024),
Forward = Vector3.new(-0.543, -0.838, -0.036),
Pos = Vector3.new(0.248, -0.187, 0.009)
}
local reloadGrip = {
Right = Vector3.new(0.040, 0.017, -0.999),
Up = Vector3.new(-0.508, 0.861, -0.005),
Forward = Vector3.new(-0.860, -0.508, -0.043),
Pos = Vector3.new(0.101, -0.136, 0.004)
}
local function fromGripTable(grip)
return CFrame.fromMatrix(grip.Pos, grip.Right, grip.Up)
end
local playerStates = {}
local function getState(player)
playerStates[player] = playerStates[player] or {
lastShot = 0,
isReloading = false,
}
return playerStates[player]
end
local function addTrail(bullet)
local att0 = Instance.new("Attachment", bullet)
att0.Position = Vector3.new(0, 0, -bullet.Size.Z / 2)
local att1 = Instance.new("Attachment", bullet)
att1.Position = Vector3.new(0, 0, bullet.Size.Z / 2)
local trail = Instance.new("Trail")
trail.Attachment0 = att0
trail.Attachment1 = att1
trail.Lifetime = 0.3
trail.Color = ColorSequence.new(Color3.fromRGB(255, 255, 100))
trail.Parent = bullet
end
local function tweenGrip(fromGrip, toGrip, duration)
local startTime = tick()
while tick() - startTime < duration do
if not Gun:IsDescendantOf(game) then break end
local alpha = (tick() - startTime) / duration
Gun.Grip = fromGrip:Lerp(toGrip, alpha)
RunService.Heartbeat:Wait()
end
if Gun:IsDescendantOf(game) then
Gun.Grip = toGrip
end
end
local function createBullet()
local bullet = Instance.new("Part")
bullet.Size = Vector3.new(0.108, 0.118, 0.214)
bullet.Color = Color3.fromRGB(248, 217, 109)
bullet.Material = Enum.Material.DiamondPlate
bullet.Anchored = true
bullet.CanCollide = false
bullet.CFrame = Gun:WaitForChild("Muzzle").CFrame
bullet.Name = tostring(math.random() * 100)
bullet.Parent = workspace
return bullet
end
local function shootBullet(originCFrame, direction, character)
local bullet = createBullet()
bullet.CFrame = CFrame.new(originCFrame.Position, originCFrame.Position + direction)
local startTime = tick()
local lastPos = originCFrame.Position
local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = {character, Gun}
rayParams.FilterType = Enum.RaycastFilterType.Exclude
local conn
conn = RunService.Heartbeat:Connect(function()
local elapsed = tick() - startTime
if elapsed > BULLET_LIFETIME then
bullet:Destroy()
conn:Disconnect()
return
end
local newPos = originCFrame.Position + direction.Unit * BULLET_SPEED * elapsed
local rayResult = workspace:Raycast(lastPos, newPos - lastPos, rayParams)
if rayResult then
local hit = rayResult.Instance
local target = hit:FindFirstAncestorOfClass("Model")
local hum = target and target:FindFirstChild("Humanoid")
if hum then
if hit.Name == "Head" then
hum:TakeDamage(DAMAGE_HEAD)
else
hum:TakeDamage(DAMAGE_BODY)
end
end
bullet:Destroy()
conn:Disconnect()
else
bullet.CFrame = CFrame.new(newPos, newPos + direction)
lastPos = newPos
end
end)
end
local function resetGrip()
Gun.Grip = fromGripTable(defaultGrip)
end
Gun.Equipped:Connect(resetGrip)
Gun.Unequipped:Connect(resetGrip)
Gun.AncestryChanged:Connect(function(_, parent)
if not parent or not parent:IsDescendantOf(game.Players) then
Gun:WaitForChild("Handle").CanTouch = false
if Gun:FindFirstChild("Barrel") then Gun.Barrel.CanTouch = false end
if Gun:FindFirstChild("Mag") then Gun.Mag.CanTouch = false end
task.delay(1.5, function()
Gun:WaitForChild("Handle").CanTouch = true
if Gun:FindFirstChild("Barrel") then Gun.Barrel.CanTouch = true end
if Gun:FindFirstChild("Mag") then Gun.Mag.CanTouch = true end
end)
end
end)
Gun.GunEvent.OnServerEvent:Connect(function(player, action, ...)
local character = player.Character
if not character then return end
local state = getState(player)
local ammo = Gun:FindFirstChild("Ammo")
local maxAmmo = Gun:FindFirstChild("MaxAmmo")
if not ammo or not maxAmmo then return end
if action == "shoot" then
local origin, direction = ...
if typeof(origin) ~= "Vector3" or typeof(direction) ~= "Vector3" then return end
if state.isReloading or tick() - state.lastShot < COOLDOWN then return end
if ammo.Value <= 0 then
Gun:WaitForChild("Empty"):Play()
end
if ammo.Value > 0 then
state.lastShot = tick()
ammo.Value -= 1
Gun:WaitForChild("Shoot"):Play()
shootBullet(Gun:WaitForChild("Muzzle").CFrame, direction, character)
end
elseif action == "reload" then
if ammo.Value >= maxAmmo.Value or state.isReloading then return end
state.isReloading = true
Gun.CanBeDropped = false
Gun.Enabled = false
Gun:WaitForChild("Reload"):Play()
task.spawn(function()
tweenGrip(fromGripTable(defaultGrip), fromGripTable(reloadGrip), 0.25)
end)
task.delay(RELOAD_TIME, function()
if ammo and maxAmmo then ammo.Value = maxAmmo.Value end
task.spawn(function()
tweenGrip(fromGripTable(reloadGrip), fromGripTable(defaultGrip), 0.25)
end)
Gun.CanBeDropped = true
Gun.Enabled = true
state.isReloading = false
end)
end
end)
-- Main follow loop
local lastDamageTime = 0
while true do
local targetPlayer, distance = findNearestPlayer()
if targetPlayer and distance > STOP_DISTANCE then
-- Move towards the player
Humanoid:MoveTo(targetPlayer.Character.HumanoidRootPart.Position)
else
-- Stop moving if no player is in range or too close
Humanoid:MoveTo(RootPart.Position)
-- Check if the NPC is touching the player
if targetPlayer and distance <= STOP_DISTANCE then
local currentTime = tick()
-- Check cooldown before dealing damage
if currentTime - lastDamageTime >= TOUCH_DAMAGE_COOLDOWN then
dealDamage(targetPlayer, DAMAGE_AMOUNT)
lastDamageTime = currentTime
-- Random chance for special attack
if math.random() < SPECIAL_ATTACK_CHANCE then
performSpecialAttack(targetPlayer)
end
end
end
end
wait(CHECK_INTERVAL)
end
Key changes and explanations:
Gun Integration: The script now assumes the gun is a child of the NPC model. It waits for the gun to load and then connects to its events.
Equipping the Gun: The NPC doesn't need to "equip" the gun in the traditional sense. The gun is always a part of the NPC.
Firing Logic: The GunEvent is fired from the gun script, and this script handles the server-side logic for shooting and reloading.
Origin and Direction: The gun script sends the origin (muzzle position) and direction of the shot to the server.
Error Handling: Added checks to ensure the gun and its components are loaded before attempting to use them.
Grip Tweens: The grip tweens are now applied to the Gun object.
Comments: Added comments to explain the changes.
Important Notes:
Gun Setup: Make sure the gun model is correctly set up with the GunEvent, Muzzle, Ammo, MaxAmmo, Shoot, Reload, and Empty objects.
Server-Side: This script is designed to run on the server. Make sure it's placed in ServerScriptService or inside the NPC model.
Testing: Thoroughly test the script to ensure the following behavior, shooting, reloading, and special attack are working as expected.
Optimization: For a large number of NPCs, consider optimizing the findNearestPlayer function to reduce performance impact. You could use spatial partitioning techniques.
This combined script should give you a functional NPC that follows players, attacks them with a gun, and has a special attack ability. Let me know if you have any further questions or need additional modifications.