So I am scripting a turret, and I need it to follow the mouse. The guns follow the Y of the mouse, and the body follows the X. So far, I've used Mouse.X and Mouse.Y and divide or subtract those numbers, but that has proven to be inefficient. Do you have any ideas on how I can do it?
RS.RenderStepped:Connect(function() print(mouse.Y/5) guns.HingeConstraint.TargetAngle = math.clamp((mouse.Y-240)/2, -45, 45) turret.Base.HingeConstraint.TargetAngle = math.clamp((mouse.X-200)/10, -45, 45) end)
The following script is from my prototype turret that uses constaints to move. It had 2 pitch and 1 yaw constraints and i had it follow a part in the workspace. You can hack it to work with the mouse. Since you have the mouse hooked up, just swap out the Firepoint varable and tweek the setting in RotatetoTarget()
function to read:
function RotatetoTarget(target, enginePos) local targetPos = target.Position local dir = (targetPos - enginePos).unit --[[.....etc...]]
to
function RotatetoTarget(target, enginePos) local targetPos = target local dir = (targetPos - enginePos).unit --[[.....etc...]]
And call the function by:
--// old while true do local FirePoint = workspace.FirePoint local DirCF = RotatetoTarget(FirePoint, Brain.Position) local Rot = getOrientation(DirCF) --// new while true do local FirePoint = Mouse.CFrame.Position local DirCF = RotatetoTarget(FirePoint, Brain.Position) local Rot = getOrientation(DirCF) --[[ ......... etc...... ]]
Code:
local Self = script.Parent local Brain = script.Parent.Brain local YawMotor = script.Parent["Motors"].Yaw local PitchMotors = {} for i=1,2 do PitchMotors[i] = script.Parent["Motors"]["Pitch"..i] end function RotatetoTarget(target, enginePos) local targetPos = target.Position local dir = (targetPos - enginePos).unit local pos = enginePos + dir return CFrame.new(pos, pos+dir) end local function getOrientation(CF) local sx, sy, sz, m00, m01, m02, m10, m11, m12, m20, m21, m22 = CF:components() local Y = math.atan2(m02, m22)*(180/math.pi)+180 local X = math.asin(-m12)*(180/math.pi)+180 local Z = math.atan2(m10, m11)*(180/math.pi)+180 return Vector3.new(X,Y,Z) end local t = 0 while true do local FirePoint = workspace.FirePoint local DirCF = RotatetoTarget(FirePoint, Brain.Position) local Rot = getOrientation(DirCF) local CanIFire = true YawMotor.TargetAngle = Rot.Y for k,v in pairs(PitchMotors) do v.TargetAngle = Rot.X -180 end wait() end
hope this helps!