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?
1 | RS.RenderStepped:Connect( function () |
2 | print (mouse.Y/ 5 ) |
3 | guns.HingeConstraint.TargetAngle = math.clamp((mouse.Y- 240 )/ 2 , - 45 , 45 ) |
4 | turret.Base.HingeConstraint.TargetAngle = math.clamp((mouse.X- 200 )/ 10 , - 45 , 45 ) |
5 | 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:
1 | function RotatetoTarget(target, enginePos) |
2 | local targetPos = target.Position |
3 | local dir = (targetPos - enginePos).unit |
4 | --[[.....etc...]] |
to
1 | function RotatetoTarget(target, enginePos) |
2 | local targetPos = target |
3 | local dir = (targetPos - enginePos).unit |
4 | --[[.....etc...]] |
And call the function by:
01 | --// old |
02 | while true do |
03 |
04 | local FirePoint = workspace.FirePoint |
05 | local DirCF = RotatetoTarget(FirePoint, Brain.Position) |
06 | local Rot = getOrientation(DirCF) |
07 |
08 |
09 | --// new |
10 | while true do |
11 |
12 | local FirePoint = Mouse.CFrame.Position |
13 | local DirCF = RotatetoTarget(FirePoint, Brain.Position) |
14 | local Rot = getOrientation(DirCF) |
15 | --[[ ......... etc...... ]] |
Code:
01 | local Self = script.Parent |
02 | local Brain = script.Parent.Brain |
03 | local YawMotor = script.Parent [ "Motors" ] .Yaw |
04 | local PitchMotors = { } |
05 | for i = 1 , 2 do |
06 | PitchMotors [ i ] = script.Parent [ "Motors" ] [ "Pitch" ..i ] |
07 | end |
08 |
09 | function RotatetoTarget(target, enginePos) |
10 | local targetPos = target.Position |
11 | local dir = (targetPos - enginePos).unit |
12 | local pos = enginePos + dir |
13 | return CFrame.new(pos, pos+dir) |
14 | end |
15 |
hope this helps!