A moving cannon with a pointing muzzle, how to make the right turn

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)

1 Like

Replace

(closestChrHRP.Position - Cannon.Position).Unit*mag

with

Cannon.CFrame:PointToObjectSpace(closestChrHRP.Position).Unit*mag

to account for the cannon’s orientation.

Alternatively, ensure that Cannon's orientation is always Vector3.new(0,0,0) regardless of how the rest of the cannon is oriented.

You should also remove the Unit*mag and the mag variable, as it is useless when you’re using LookAt anyway.

did this but it doesn’t work

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
		CannonM6D.C0 =  CFrame.lookAt(CannonM6D.C0.Position, Cannon.CFrame:PointToObjectSpace(closestChrHRP.Position))
	end
	task.wait()
end

One method should be this if you are working with motor6ds

There is another formula in my CFrame tutorial which is more simpler

1 Like