Hello.
Working on a gun turret for my japanese dive bomber.
It works, but it fires the wrong direction which is rather annoying
Code:
wait(7.1)
local plane = script.Parent.Parent
if plane.Parent == workspace.RedPlanes then
targets = workspace.BluePlanes
bull = game:GetService("ReplicatedStorage").Ammo.JB
end
if plane.Parent == workspace.BluePlanes then
targets = workspace.BluePlanes
bull = game:GetService("ReplicatedStorage").Ammo.AB
end
local function FireGuns(angle)
for i,v in pairs(script.Parent:GetChildren()) do
if v:IsA("BasePart") then
local bullet = bull:Clone()
bullet.Orientation = angle * -1
bullet.Position = v.Position
bullet.Parent = workspace
wait(0.4)
end
end
end
local function findNearestEnemy()
local MaxDistance = 99999
local nearestEnemy = nil
for i, enemy in pairs(targets:GetChildren()) do
if enemy then
local distance = (plane.PrimaryPart.Position - enemy.PrimaryPart.Position).magnitude
if distance < MaxDistance and enemy.Health.Value > 0 and distance < 1500 then
nearestEnemy = enemy
MaxDistance = distance
end
end
end
return nearestEnemy
end
local function FindAngle(nearestEnemy)
local origincframe = plane.Engine.BodyGyro.cframe
local dir = (plane.PrimaryPart.Position - nearestEnemy.PrimaryPart.Position).unit
local spawnPos = plane.PrimaryPart.Position
local pos = spawnPos + dir
local angle = pos+dir
return angle
end
while wait() do
local nearestEnemy = findNearestEnemy()
if nearestEnemy then
local angle = FindAngle(nearestEnemy)
FireGuns(angle)
end
end
All help is appreciated.
Thanks!