I need help in creating a better turret/cannon

Hi! I’m trying to make a ship cannon that targets the closest player and has a limited field of view (horizontal) and range and I’ve only made this very rough script which I think I think the experts here can assist me in this. So far, I don’t need the shooting part of the turret, just the aiming.

Before I touch on the script, this is what I have on the workspace:
image

I was also unable to create a line that touches on the rotation of the cannon (not wanting the cannon to rotate up and down) so I had this on the BodyGyro but I think there’s a way via script:
image

Lastly, I lack the ability to script well, so using okeanskiy’s tutorial on Vector3 Dot Product (Vector3 Dot Product: Calculating NPC Field of View (Roblox Studio) - YouTube), I’ve made it to limit the field of view of the cannon, however I’m still unable to limit the range of the FoW as this script makes the cannon able to detect players in infinity. In addition, the script only focuses on ONE player and will focus on the player even if there is another player close to the cannon itself and if it’s out of sight.

This is the ‘cannon’ itself:
image

local GYRO = script.Parent.Object.BodyGyro
local GYROPOS = script.Parent.Object.BodyPosition
local RS = game:GetService("RunService")
local PLAYERS = game.Players
local OBJ = script.Parent.PrimaryPart
local BASE = script.Parent.Base
local FOCUS = workspace.Focus

while RS.Heartbeat:Wait() do
	GYROPOS.Position = BASE.Position + Vector3.new(0, 1, 0)
	
	for i,PLR in pairs(PLAYERS:GetPlayers()) do
		local CHAR = PLR.Character
		local CHARFOCUS
		if CHAR and CHAR:FindFirstChild("Humanoid") then

			if not CHARFOCUS then CHARFOCUS = CHAR end

			local CannonToCharacter = (CHARFOCUS.PrimaryPart.Position - BASE.Position).Unit 
			local CannonView = BASE.CFrame.LookVector
			local DotProduct = CannonToCharacter:Dot(CannonView)

			if DotProduct > .5 then
				GYRO.CFrame = CFrame.new(OBJ.Position, CHARFOCUS.PrimaryPart.Position)
			else
				print("not in view")
			end	
			
		end
	end
	
end
2 Likes