Rotate a Turret that is Already Rotated

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

4 Likes

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

This doesn’t work, anything I try comes with CFrame and Vector3 incompatibility in multiple places

This fixed it, I just changed up the order and really have no idea why this works and the previous code didn’t

local rx, ry, rz =  CFrame.new(Turret.Rotate.Position,Vector3.new(extraInfo.Position.X,Turret.Rotate.Position.Y,extraInfo.Position.Z)):ToOrientation()
local rxo,ryo,rzo = (Main.Main.PilotSeat.CFrame.Rotation):ToOrientation()
local aimDirection = CFrame.Angles(0,ry-ryo,0)
Turret.Rotate.Motor6D.C1 = aimDirection

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.