Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Gun flies around the enemy. How can i fix this?

So I have solved the problem of the enemy not moving by manipulating its PrimaryPart. I have been debugging this since the afternoon, and I still can't get it why the gun just flies around that guy like an angel. Additionally, the gun is out of control since it's shooting multiple bullets at the same time.

This is whats happening here: https://www.youtube.com/watch?v=QGBLK01oCrw

--DEFINING--

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local bullet = ReplicatedStorage:WaitForChild("7.62x51mmNATO")

local user = script.Parent
local sound = user.G3.Firesound
local casing = ReplicatedStorage:WaitForChild("shellEject")
local hrp = user.PrimaryPart.Position
local hrpnp = user.PrimaryPart

local gun = user.G3
local br = gun.Handle
local human = nil
local torso = nil

local fireRate = 0.1
local bulletSpeed = 200
local aggroDist = 50
local dmg = 10

print ("succesfully loaded all terms")

--FIRING--

while wait(fireRate) do
	local target = nil
	for i, v in pairs(game.Workspace:GetChildren()) do
		human = v:FindFirstChild("Humanoid")
		torso = v:FindFirstChild("UpperTorso")
		if human and torso and human.Health > 0 then
			if (torso.Position - hrp).magnitude < aggroDist then
				local bulletRay = Ray.new(hrp, (torso.Position - hrp).Unit * aggroDist)
				local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(bulletRay, {user,hrpnp})
				if hit == torso then
					target = torso
				else
					target = nil
				end
			end
		end
--GUN MECHANICS--		
		if target then
			torso = target
			user:SetPrimaryPartCFrame(CFrame.new(hrp,Vector3.new(torso,hrp,torso)))
			hrpnp.CFrame = CFrame.new(hrp, torso.Position)
			local newBullet = bullet:Clone()
			--[[local fire = sound:Clone()
			fire.Parent = gun
			newBullet.Position = hrp
			newBullet.Parent = workspace.Camera]]--
			
			--newBullet.Velocity = br.CFrame.LookVector * bulletSpeed
			
			--[[newBullet.Touched:Connect(function(objectHit)
				local human = objectHit.Parent:FindFirstChild("Humanoid")
				if human then
					human:TakeDamage(dmg)
					wait(1)
					newBullet:destroy()
				else
					human = nil
				end
			end)]]
		end
	end
end



1 answer

Seems like I have figured it out what's the problem, and it's that the tool is a nuisance.

I replaced the tool with a model and it's now fine.

This discussion is preserved as it was. New answers, comments, and votes are closed.