Gun projectile Script, any way to improve it?

Hello, I’ve made a laser pistol that shoots a projectile, the code is working.
I would just like to know if there is any better or more efficient way to make this
I already tried fastcast but it hurts my brain and i cant get it to work


fire.OnServerEvent:Connect(function(player, direction)
	local char = player.Character
	local hum = char.Humanoid
	local pistol = char.LaserPistolMesh
	
	local bullet = Instance.new("Part", workspace)
	bullet.Shape = Enum.PartType.Ball
	bullet.Size = Vector3.new(0.4,0.4,0.4)
	bullet.CanCollide = false
	bullet.Color = Color3.fromRGB(160, 255, 236)
	bullet.Position = pistol.GunBarrel.Position
	
	local bulletVelocity = Instance.new("BodyVelocity", bullet)
	bulletVelocity.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
	bulletVelocity.P = math.huge
	bulletVelocity.Velocity = direction.lookVector * bulletSpeed
	
end)


1 Like

LaserPistolMesh is not guaranteed to be equipped by the player especially if the remote was fired unnecessarily.

local pistol = char.LaserPistolMesh

You’re creating a part and immediately parenting it to workspace and then setting it’s properties after which is bad practice. Create the part, set it’s properties and then parent it.

local bullet = Instance.new("Part", workspace)
	bullet.Shape = Enum.PartType.Ball
	bullet.Size = Vector3.new(0.4,0.4,0.4)
	bullet.CanCollide = false
	bullet.Color = Color3.fromRGB(160, 255, 236)
	bullet.Position = pistol.GunBarrel.Position

Same goes for this:

	local bulletVelocity = Instance.new("BodyVelocity", bullet)
	bulletVelocity.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
	bulletVelocity.P = math.huge
	bulletVelocity.Velocity = direction.lookVector * bulletSpeed

Also, you may want to rate-limit your remotes. You don’t want an exploiter to be spamming the remote creating tons of bullets.

How I would write your code
local COOL_DOWN = 1

local Cooldowns = {}

fire.OnServerEvent:Connect(function(player, direction)
    if (Cooldowns[player.Name] and os.time() - CoolDowns[player.Name] < COOL_DOWN) then return end

    Cooldowns[player.Name] = os.time()

	local char = player.Character
	local hum = char.Humanoid
	local pistol = char:FindFirstChild("LaserPistolMesh")
    if not (pistol) then return end
	
	local bullet = Instance.new("Part")
	bullet.Shape = Enum.PartType.Ball
	bullet.Size = Vector3.new(0.4,0.4,0.4)
	bullet.CanCollide = false
	bullet.Color = Color3.fromRGB(160, 255, 236)
	bullet.Position = pistol.GunBarrel.Position
    bullet.Parent = workspace
	
	local bulletVelocity = Instance.new("BodyVelocity")
	bulletVelocity.MaxForce = Vector3.new(math.huge,math.huge,math.huge)
	bulletVelocity.P = math.huge
	bulletVelocity.Velocity = direction.lookVector * bulletSpeed
    bulletVelocity.Parent = bullet	

end)
1 Like