Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How would I make a turret move by following the mouse?

Asked by
niroqeo 123
4 years ago

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?

1RS.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)
5end)

1 answer

Log in to vote
1
Answered by
TGazza 1336 Moderation Voter
4 years ago

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:

1function RotatetoTarget(target, enginePos)
2    local targetPos = target.Position
3    local dir = (targetPos - enginePos).unit
4    --[[.....etc...]]

to

1function RotatetoTarget(target, enginePos)
2    local targetPos = target
3    local dir = (targetPos - enginePos).unit
4    --[[.....etc...]]

And call the function by:

01--// old
02while true do
03 
04    local FirePoint = workspace.FirePoint
05    local DirCF = RotatetoTarget(FirePoint, Brain.Position)
06    local Rot = getOrientation(DirCF)
07 
08 
09--// new
10while true do
11 
12    local FirePoint = Mouse.CFrame.Position
13    local DirCF = RotatetoTarget(FirePoint, Brain.Position)
14    local Rot = getOrientation(DirCF)
15--[[ ......... etc...... ]]

Code:

01local Self = script.Parent
02local Brain = script.Parent.Brain
03local YawMotor = script.Parent["Motors"].Yaw
04local PitchMotors = {}
05for i=1,2 do
06    PitchMotors[i] = script.Parent["Motors"]["Pitch"..i]
07end
08 
09function 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)
14end
15 
View all 38 lines...

hope this helps!

0
Thanks for helping! It's been a while, and I will go back to the turret project eventually. I'm working on something else right now, so when I go back I will read this post again. niroqeo 123 — 4y
Ad

Answer this question