Hi! I have a model of a cannon, this model can move and turn in different directions, the muzzle of the gun cannon is attached using a 6D motor, the muzzle must turn towards the character. When the model’s orientation is Vector3.new(0,0,0), then the muzzle of the cannon is pointed correctly, but when the orientation of the model of the cannon is changed, the muzzle of the cannon is pointed incorrectly.
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")
local TestRot = script.Parent
local Root = TestRot.Root
local Cannon = TestRot.Cannon
local CannonM6D = Root.CannonM6D
function getClosestChrPos(posNPC)
local minDistance = 1000000
local chrMin, chrHRPMin , chrHMin
for i, v in ipairs(Players:GetPlayers()) do
if v.Character then
local chrHRP = v.Character:FindFirstChild("HumanoidRootPart")
if chrHRP then
local diff = posNPC - chrHRP.Position
if diff.Magnitude < minDistance then
minDistance = diff.Magnitude
chrMin = v.Character
chrHRPMin = v.Character.HumanoidRootPart
chrHMin = v.Character.Humanoid
end
end
end
end
return chrMin, chrHRPMin, chrHMin
end
while true do
-- find the coordinates of the nearest character to turn the gun towards him
local closestChr, closestChrHRP, closestChrH = getClosestChrPos(Cannon.Position)
if closestChrHRP then
local mag = (closestChrHRP.Position - Cannon.Position).Magnitude
CannonM6D.C0 = CFrame.lookAt(CannonM6D.C0.Position, (closestChrHRP.Position - Cannon.Position).Unit*mag)
end
task.wait()
end
Cannon Test.rbxl (40.0 KB)