This scirpt is very costly and drops Heartbeat down to 7 and FPS from 60 to 14

Is there anyway I can optimise this script while still making the Gun welds move smoothly? I know its this function as I commented it out and everything worked fine.

function turn(num, flip)
	local MouseLook = ((script.Parent["Gun"..num].PrimaryPart.Position - turnTo) * Vector3.new(1, 0, 1)).unit
	local MouseBearing = math.atan2(MouseLook.x, MouseLook.z)

	if flip then
		MouseBearing = -MouseBearing
	end
	local distanceTO = MouseBearing - script.Parent["Gun"..num].PrimaryPart.Orientation.Y

	script.Parent.Model["Gun"..num.."MainPoint"].Weld.C1 = script.Parent.Model["Gun"..num.."MainPoint"].Weld.C1:Lerp(CFrame.new(0,0,0) * CFrame.fromEulerAnglesXYZ(0, (MouseBearing)-math.rad(script.Parent.Model.PrimaryPart.Orientation.Y), 0), 1)

	local TankElevate = script.Parent["Gun"..num].Gun.Fire1.CFrame.lookVector.y
	local MouseElevate = math.asin((turnTo - script.Parent["Gun"..num].Gun.Fire1.CFrame.p).unit.Y)	
	MouseElevate = math.max(math.rad(-12), math.min(math.rad(25), MouseElevate))

	script.Parent["Gun"..num].Gun.Fire1.Fire1.C1 = script.Parent["Gun"..num].Gun.Fire1.Fire1.C1:Lerp(CFrame.new(1,0,7.5)* CFrame.fromEulerAnglesXYZ(-MouseElevate, 0, 0), 1)	
	script.Parent["Gun"..num].Gun.Fire2.Fire2.C1 = script.Parent["Gun"..num].Gun.Fire2.Fire2.C1:Lerp(CFrame.new(-1,0,7.5)* CFrame.fromEulerAnglesXYZ(-MouseElevate, 0, 0), 1)	
end

while true do
	local num = 1
	if turnTo ~= nil and server.JuggernaughtHandler.Health.Value > 0 then
		local BaseRot = script.Parent.Model.PrimaryPart.CFrame
		BaseRot = BaseRot - BaseRot.p

		turn("2", false)
		turn("3", false)
		turn("4", false)
		turn("1", false)
	end	
	wait(0.3)
end

This is the ship

1 Like

You could instead of using while loop run the code when a certain value gets changed and for gun rotation you could use constraints that work smoothly through using physics and all you will need to do is just calculate the angle for them to rotate at

That’s a lot of trig steps happening in those calculations, might be the cause of lag.

Try comparing your performance with my turret system which doesn’t use trigonometry sin or cos, instead I convert from CFrame to Orientation, clamp it then convert it to CFrame.

Btw, what’s the script activity of this script?

Also your script uses a lot of indexing, all those script.Parent is an additional step and can cause lag, this optimization tutorial should explain why.

Yooo that looks sick just give me a little while to figure that all out.