Unsure of how to fix Turret lag

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve?
    Fix Turret lag.

  2. What is the issue?
    Turret system works fine, but once placed in a game with many assets it lags behind. It’s to the point where the bullets render useless and don’t even move from the barrel. I am still very new to scripting and almost all of my scripts heavily depend on information I find throughout the devforum.

This is all handled in a server script, which I presume to be the problem based on what I’ve read. However, due to my lack of knowledge, I’m unsure how to handle the Bullets through the client.

local p = script.Parent
local CameraHead = p.Camera:WaitForChild("CameraHead")
local CameraWeld = p.CameraMount:WaitForChild("CameraHead")
local tweenService = game:GetService("TweenService")

local tweenInfo = TweenInfo.new(
	4,									
	Enum.EasingStyle.Sine,				
	Enum.EasingDirection.InOut,			
	-1,									
	true,								
	1									
)

local goal = {C0 = CameraWeld.C0 * CFrame.Angles(0, math.rad(-90), 0)}
local tween = tweenService:Create(CameraWeld, tweenInfo, goal)

tween:Play()

function visualizeRay(origin, direction)
	local part = Instance.new("Part")
	part.Transparency = 0.98
	part.Anchored = true
	part.CanCollide = false
	part.Material = Enum.Material.Neon
	part.Color = Color3.fromRGB(255, 0, 0) 
	part.Size = Vector3.new(0.2, 0.2, direction.Magnitude)
	part.CFrame = CFrame.new(origin, origin + direction) * CFrame.new(0, 0, -direction.Magnitude / 2) 
	part.Parent = workspace

	
	game:GetService("Debris"):AddItem(part, 0.1)
end

function raycast()
	local results = {}

	for _, attachment in next, CameraHead:GetChildren() do
		if attachment:IsA("Attachment") and attachment.Name == "RaycastAttachment" then
			for _, directPart in next, CameraHead:GetChildren() do
				if directPart:IsA("BasePart") and directPart.Name == "direct" then
					local origin = attachment.WorldPosition
					local length = 50
					local direction = directPart.CFrame.LookVector * length

					local raycastParams = RaycastParams.new()
					raycastParams.FilterDescendantsInstances = {attachment, CameraHead, p}
					raycastParams.FilterType = Enum.RaycastFilterType.Exclude

					visualizeRay(origin, direction)
					
					results[attachment] = workspace:Raycast(origin, direction, raycastParams)


					if results[attachment] then
						local hitInstance = results[attachment].Instance
						local char = hitInstance.Parent
						if char:FindFirstChild("HumanoidRootPart") then
							CameraHead.Alert:Play()
							tween:Pause()
							
							local function RandomCone(axis: Vector3, angle: number)
								local cosAngle = math.cos(angle)
								local z = 1 - math.random()*(1 - cosAngle)
								local phi = math.random()*math.pi*2
								local r = math.sqrt(1 - z*z)
								local x = r * math.cos(phi)
								local y = r * math.sin(phi)
								local vec = Vector3.new(x, y, z)
								if axis.Z > 0.9999 then
									return vec
								elseif axis.Z < -0.9999 then
									return -vec
								end
								local orth = Vector3.zAxis:Cross(axis)
								local rot = math.acos(axis:Dot(Vector3.zAxis))
								return CFrame.fromAxisAngle(orth, rot) * vec
							end
							
							local function LaunchProjectile()
								
								local SPREAD = math.rad(45)
								local bulletSpeed = 89
								local bulletPrefab = game.ReplicatedStorage:WaitForChild("Bullet") 
								local barrel = p.Camera.Blaster.Barrel 
								local bullet = bulletPrefab:Clone()
								local targetHit = false
								
								
								bullet.CFrame = barrel.CFrame
								bullet.Parent = workspace
								
								local spreadAmount = math.rad(20)
								
								local bodyVeloc = Instance.new("BodyVelocity",bullet)
								bullet.BodyVelocity.Velocity = RandomCone(CameraHead.CFrame.LookVector, spreadAmount) * bulletSpeed
								
								game.Debris:AddItem(bullet, 2)

								bullet.Touched:Connect(function(hit)
									local humanoid = hit.Parent:FindFirstChild("Humanoid")
									if humanoid ~= nil and targetHit == false then
										humanoid:TakeDamage(35)
										targetHit = true
										bullet.flesh_impact_bullet1:Play()
									end
									
								end)
							end

							
							for i = 1, 36 do
								LaunchProjectile()
								CameraHead["Machine Gun single shoot"]:Play()
								wait(0.1)
							end
							
							tween:Play()
							
						end
					end
				end
			end
		end
	end
end

while true do 
	raycast()
	wait(0.1)
end

So this one just uses tweenservice, in which you didn’t know, sometimes lags when there are too many physical parts on the workspace.

Try making an animation that doesn’t rely on the tweenservice.

1 Like

Will this help with the bullets lagging though? The tween is only meant for rotating the turret itself as showed in the video which I haven’t ran into any issues with, if you take a quick look in the script I use a body velocity in order to move the bullets.

Just create a remote event that tells the client what the new CFrame of the turret should be, and on the client just create a tween and move it to that CFrame. If replication is an issue, you can set the CFrame of the turret on the server without tweening, and then tween on the client.

Also regarding the bullets, if you mean that the bullets only appear for a split second and don’t seem to actually fly anywhere, that might be because the bullets are so fast that the roblox physics engine can’t keep up. I’d recommend using a non-physics based method to move your bullets.

1 Like

Thank you! Would raycasting the bullets be a better solution? If so should I use a module to quickly get the job done? I’ve heard of a module called FastCast but never looked into it.

If you still want the bullets to be visible, you could either tween them, or there’s a really helpful module for creating raycast projectiles. It’s called FastCast and it’s pretty cool and will most likely solve your problem.

FastCast uses raycasts to create a path where the projectile will go, and then uses RunService and CFrames to push the projectile along it’s path, giving it both travel time, and ensuring it’ll travel in the direction you sent it without hiccups.

1 Like

Sounds great, I’ll take a look into it! Thank you for your time! I appreciate the help, take care. :grin:

1 Like

If u have any trouble with fastcast just DM me. There’s an issue where the first frame of the projectile won’t render, but I fixed it so if u have that problem i can fix it.

1 Like

Thank you, I will keep that in mind and reach out if I have any issues. Tomorrow I plan to take a look into FastCast and experiment with the module a little before I try adding it to my current system.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.