Why doesnt raycast work after a bit?

Hello!
I was working on a NPC that wields a gun, and well, shoots it.
My script works, but after the player moves, it just stops working.

heres my code:

--[[
 ------------------------------------------------------------------------------------------------------------------------
 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 ------------------------------------------------------------------------------------------------------------------------
  _    _  ____  _      _____     ____  _   _ _ 
 | |  | |/ __ \| |    |  __ \   / __ \| \ | | |
 | |__| | |  | | |    | |  | | | |  | |  \| | |
 |  __  | |  | | |    | |  | | | |  | | . ` | |
 | |  | | |__| | |____| |__| | | |__| | |\  |_|
 |_|  |_|\____/|______|_____/   \____/|_| \_(_)
 ------------------------------------------------------------------------------------------------------------------------
 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 ------------------------------------------------------------------------------------------------------------------------
 
 If you're reading this, you may think i'm some loser who followed a tutorial for this (which I kinda did)
 
 but the tutorial used variables that were deprecated.
 I had to find a way to fix these variables, I also had to add a bunch of other stuff to make the AI look good.
 I only followed the tutorial on how to use raycasting. NOTHING ELSE. No some sort of "damage" script.
 
 Anyways, if you are going to look at this script, it's really messy (I think)
 
 so, enjoy yourself!
 ------------------------------------------------------------------------------------------------------------------------
 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 ------------------------------------------------------------------------------------------------------------------------
]]

local replicatedStorage = game:GetService("ReplicatedStorage")
local players = game:GetService("Players")


local bullet = replicatedStorage.MapStuff:WaitForChild("Bullet")


local parent = script.Parent
local myTorso = parent.Torso
local hrp = parent.HumanoidRootPart
local hum = parent.Humanoid
local animator = hum.Animator
local deagle = parent.deagle
local firePoint = parent.FirePoint


local values = parent.Values
local walkSpeed = values.WalkSpeed.Value
local health = values.Health.Value
local damage = values.Damage.Value
local distance = values.Distance.Value
local cooldown = values.CoolDown.Value
local ammo = values.Ammo.Value


local bulletHit = false
inFire = false


local compatible = {"Torso", "Left Arm", "Right Arm", "Left Leg", "Right Leg", "HumanoidRootPart"}
local critical = {"Head"}


local fireAnim = Instance.new("Animation", parent)
fireAnim.Name = "FireAnim"
fireAnim.AnimationId = "rbxassetid://11572460578"

local reloadAnim = Instance.new("Animation", parent)
reloadAnim.Name = "ReloadAnim"
reloadAnim.AnimationId = "rbxassetid://11573779972"

hum.WalkSpeed = walkSpeed
hum.MaxHealth = health
hum.Health = health

while task.wait() do
	
	local target = nil
	
	for i, v in pairs(game.Workspace:GetChildren()) do
		if (v ~= parent) then
			local humanoid = v:FindFirstChild("Humanoid")
			local torso = v:FindFirstChild("Torso")
			local hrp = v:FindFirstChild("HumanoidRootPart")

			if humanoid and humanoid.Health >= 0 and torso and hrp and (torso ~= myTorso) then
				if (v.Torso.Position - parent.FirePoint.Position).Magnitude < distance then		
					local bulletRay = workspace:Raycast(firePoint.Position, firePoint.CFrame.LookVector * distance)
					
					--parent:PivotTo(CFrame.lookAt(parent.HumanoidRootPart.Position, hrp.Position * Vector3.new(1, 0 ,1) + parent.HumanoidRootPart.Position * Vector3.new(0, 1, 0)))
	
					if bulletRay then
						if (bulletRay.Instance.Parent ~= parent:GetChildren()) and table.find(compatible, bulletRay.Instance.Name) then
							target = torso
						end
					end
				end	
			end
		end
		if target and not inFire then
			inFire = true


			if ammo == 0 then
				animator:LoadAnimation(reloadAnim):Play()
				wait(.25)
				deagle.mag.Transparency = 1
				wait(.75)
				deagle.mag.Transparency = 0
				wait(2.4)
				ammo = 10
				wait(.2)
			end


			--// randomizing stabilization \\--
			local X1,Y1,Z1 = math.random(0.4, 2),math.random(0.4, 2),math.random(0.4, 2)
			parent.FirePoint.Orientation = Vector3.new(X1,Y1,Z1)

			if workspace:FindFirstChild("Bullet") then
				workspace.Bullet:Destroy()
			end
			local torso = target

			animator:LoadAnimation(fireAnim):Play()

			wait(0.3)

			deagle.MuzzleFlash.MuzzleEffect.Enabled = true
			deagle.MuzzleFlash.PointLight.Enabled = true
			parent.FirePoint.Fire:Play()

			local bullet = bullet:Clone()
			bullet.CFrame = parent.BulletSpawn.CFrame

			bullet.Parent = game.Workspace

			ammo -= 1	

			bullet.Touched:Connect(function(hit)
				if hit.Parent ~= nil then
					local humanoid = hit.Parent:FindFirstChild("Humanoid")
					if humanoid and (hit.Parent ~= parent) and not bulletHit then
						bulletHit = true

						if not table.find(critical, hit.Name) then
							humanoid:TakeDamage(damage)
							print("bullet hit "..hit.Name)
						else
							humanoid:TakeDamage(70)
							print("bullet hit "..hit.Name..". Critical hit.")
						end

						task.wait(2)
						bulletHit = false

						bullet:Destroy()
						inFire = false
					end
				end
				task.wait(0.05)
				firePoint.Orientation = Vector3.new(0, 0, 0)
				deagle.MuzzleFlash.MuzzleEffect.Enabled = false
				deagle.MuzzleFlash.PointLight.Enabled = false
				task.wait(cooldown)
				inFire = false
			end)
		end
	end
end

Any help is appreciated
(Edit: It works, but only sometimes. Its firing hitbox is extremely broken. I dont know how to fix.)

2 Likes

Can you elaborate on the issue a little more? What isn‘t working?

1 Like

Alright… so, my problem is that the npc just likes to give up on life some times and not.
Basically, the hitbox is actually trash.

He hits you if you stand still. Then he doesnt. Then he does. Then he doesnt. I will send a video soon. ( I also updated my script a bit, ill edit the current script in my post)

Oof… yeah. You’re causing many memory leaks (I think) by doing all of this in a while loop. Especially how you’re connecting the Touched event.

I’d say this needs a rewrite. Having it in a loop is probably the culprit, try scripting it like a normal gun, and then having a couple of events that a script in the NPC fires regularly.

ok

(AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA)

1 Like

Also, thanks for replying. It was kinda hard to find someone that will help. I will just write a normal gun script, then connect it to a bindable event.’

(Forgot to say this; my code works now, but I might still rewrite it.

Im pretty sure roblox it self made a raycast laser gun type tutorial

I dont want to follow tutorial, tutorial lame :frowning:

Tutorials are helpful and great for learning

1 Like

You must be really new lol. Tutorials are the most helpful tool for everyone. I have coded for 5 years and still use tutorials

2 Likes

If you didnt get it, it was a joke. (Also, I am not new. Just kinda dumb.

Yea that joke was real bad lmao

1 Like

ok. Thanks for the encouraging words