Cannon Aim to Mouse

Hello, I’m making a cannon that aims at the mouse:
Screenshot 2023-11-06 192123

Only problem is I don’t know to adjust the weld to aim at the mouse. This script below doesn’t really work.

Script:

local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()

local boat = workspace:WaitForChild("Boat")
local cannon = boat:WaitForChild("Cannon")
local origin = cannon:WaitForChild("Aim"):WaitForChild("Weld")
local barrel = cannon:WaitForChild("Barrel")

mouse.Move:Connect(function()
	local c0 = CFrame.new(origin.C0.Position, mouse.Hit.Position) * CFrame.Angles(0, -math.pi/2, 0)
	origin.C0 =  c0
end)

Thank you.

Bump
:facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch::facepunch:

Motor6D are offset this means that they are in local space, you have to convert the CFrame your constructing into local space for it too work

I don’t get what you mean. The script is already a local script and it’s a weld? Please correct me thank you!

I found a post, but now it just moves circular. Ex: moving up make the cannon turn right, moving down makes cannon move left…

Script:

	local part1Pos = mouse.Hit.Position
	local direction = (mouse.Hit.Position - aim.Position).Unit * 100
	
	local targetCf = CFrame.new(aim.Position, part1Pos + direction) * CFrame.Angles(0, -math.pi/2, 0)
	weld.C0 = aim.CFrame:Inverse() * targetCf

Does this work?

local mousePosInObjectSpace = weld.Part0.CFrame:Inverse() * mouse.Hit.Position
weld.C0 = CFrame.lookAt(weld.C0.Position, mousePosInObjectSpace) * CFrame.Angles(0, -math.pi/2, 0)

Nope it works like a helicopter. Here’s the file:
Boat.rbxm (12.0 KB)

I managed to make it work somewhat. Now it can turn left and right accurately, but it can’t go up and down. Also it sort of leans when I want it to be completely straight.

Updated script:

local pivot = aim.CFrame
	local lookAtCFrame = CFrame.lookAt(pivot.Position, mouse.Hit.Position)
	local rotatedCFrame = lookAtCFrame * CFrame.Angles(0, -math.pi/2, 0)
	weld.C1 = rotatedCFrame.Rotation

New script:

	local pivot = aim.CFrame
	local lookAtCFrame = CFrame.lookAt(pivot.Position, mouse.Hit.Position)
	local rotatedCFrame = lookAtCFrame * CFrame.Angles(0, -math.pi/2, 0)
	local x, y, z = rotatedCFrame:ToEulerAnglesYXZ()
	weld.C1 = CFrame.Angles(x, y, 0)

Bump. I found a bug where if you’re towards the right of the baseplate it just breaks.