I have a turret on a spaceship. Clicking makes the turret rotate and point towards the mouse click, and this all works.
HOWEVER, it only works when the ship is pointing directly North or South (Orientation 0 or -180). If it’s rotated in another direction, the turret rotation is off.
Turret is a model, Turret.Rotate is the part of it that actually rotates (the rest of the model is welded to Rotate). Main.Main.PilotSeat is the driver seat.
Code: extraInfo is Mouse.Hit
local rx, ry, rz = CFrame.new(Turret.Rotate.Position,extraInfo.Position):ToOrientation()
local aimDirection = CFrame.Angles(0,ry,0)
local rxo,ryo,rzo = (Main.Main.PilotSeat.CFrame):ToOrientation()
local aimOffset = CFrame.Angles(0,ryo,0)
Turret.Rotate.Motor6D.C1 = aimDirection*aimOffset
Video:
The turret rotates each time I click
The video starts with the ship pointing North
You could calculate the turret rotation in the local space of the spaceship.
local extraInfo = Mouse.Hit
local turretPosition = Turret.Rotate.Position
local turretRotation = CFrame.new(turretPosition, extraInfo.Position)
-- Get the turret rotation in the local space of the spaceship
local localTurretRotation = Main.Main.PilotSeat.CFrame:pointToObjectSpace(turretRotation)
-- Extract the Y rotation angle
local _, yAngle, _ = localTurretRotation:ToOrientation()
-- Apply the turret rotation offset based on the spaceship's orientation
local spaceshipOrientation = Main.Main.PilotSeat.CFrame
local adjustedRotation = CFrame.Angles(0, yAngle, 0)
local finalRotation = spaceshipOrientation * adjustedRotation
-- Apply the final rotation to the turret
Turret.Rotate.Motor6D.C1 = finalRotation