I’m designing a cannon AI that fires projectiles in an arc toward your position once you get within its aggro range. I based my approach on this video and when I implement it just like this (with an anchored orb shooting the projectiles) it works perfectly. However, I don’t want a floating ball, I want an AI like this to shoot the projectiles:
This AI is supposed to orient its barrel in the direction of the arc and fire the projectile high into the air like an artillery cannon. However, when I test it in-game, this is what happens:
I’ve double-checked my code and used print()
statements to look at the position it’s firing at, and they both match in the code. I cannot figure out why it’s firing at someplace else. Notice that the turret’s barrel isn’t necessarily facing me, either.
Here’s all the relevant code. I’ll tell you right now that this is all on the client (hence the remote events) and that the welds are not what is causing the issue, as I tested the cannon firing head-on at me and it aimed the barrel properly.
-- calculates the pathway of a cannon bullet
local function calculateFlightPath(target, turret)
local start = turret:FindFirstChild("Barrel", true).WorldCFrame.Position
local destination = target
print(players.LocalPlayer.Character.PrimaryPart.Position)
local direction = destination - start
local duration = 5.5
destination = target * duration
direction = destination - start
local force = direction / duration + Vector3.new(0, workspace.Gravity * duration * 0.5, 0)
return force
end
-- fires a turret bullet
local function fire(turret)
local bullet = projectiles:FindFirstChild(turret.Name) and projectiles[turret.Name]:Clone() if not bullet then return end
bullet.CFrame = turret:FindFirstChild("Barrel", true).WorldCFrame
bullet.Parent = workspace
if turret.Name == "Cannon" then
bullet:ApplyImpulse(calculateFlightPath(turret.Parent:GetAttribute("Target"), turret) * bullet.Mass)
task.wait(1)
bullet.Touched:Connect(function(part)
if not turret:FindFirstChild(part, true) then
enemyAttack:FireServer(turret.Parent, turret.PrimaryPart.Position, part.Name, bullet.Position)
bullet:Destroy()
end
end)
end
end
local aimer = turret:FindFirstChild("Aimer", true)
local cFrame = CFrame.lookAt(aimer.WorldPosition, calculateFlightPath(folder:GetAttribute("Target"), turret))
local relativeCFrame = turret.PrimaryPart.CFrame:ToObjectSpace(cFrame)
local x, y, z = relativeCFrame:ToOrientation()
weldUpDown.C0 = offsetUD * (CFrame.Angles(x, 0, 0)):ToWorldSpace()
weldLeftRight.C0 = offsetLR * (CFrame.Angles(y, 0, 0)):ToWorldSpace()
Please let me know if you need any more information.