Is it possible to limit rotation for a stationary object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By System_Error

Hi all.

I had an idea pop into my head, but would like to know a bit more before I start poking around with it. Say, for example, I had a turret. This turret is on the back of a spaceship. How would I be able to limit how far the weapon can turn? Maximum angle I was thinking of for either direction was 45°.

:bust_in_silhouette: Reply From: p7f

Hi, you can use clamp. I suppose that you determine the desired rotation somehow programatically, then you can clamp it like this:

var m_rotation = get_desired_rotation() #your function to get rot
m_rotation = clamp(m_rotation, -PI/4, PI/4) #-45° to 45°
$Turret.rotation = m_rotation

I’m assuming you are calling this from the parent node of the Turret.

If I’m understanding this correctly, we get the desired rotation of the turret, check if it is between the two limiters, and if it is, set the rotation. If it isn’t, set the rotation to the limit the rotation is trying to surpass.

System_Error | 2018-12-13 19:04

Yes, that is what clamp does… isn’t it what you need?

p7f | 2018-12-13 19:13

I believe so. Thanks!

System_Error | 2018-12-13 19:48

I poked some of this code in, and had a laugh with the instant-snapping of the turret to the turn-limit. Seems like I need a few more things before it’ll work with what I’ve got right now, but a little editing of this, and it’ll be perfect for a turret in the middle of the screen, on a tower, fending off against enemies coming from eight differing directions.

System_Error | 2018-12-14 01:18

:bust_in_silhouette: Reply From: Sam_Hollands_Godot

Dude, this may help, you can actually simply this into one line of code, it works to, no jumping to the degrees. I am actually quite an inexperienced programmer myself and couldn’t find a tutorial on clamps, sooo did a bit of research and played about with the function. Hopefully should work, tell me if it doesn’t!

rotation = clamp(rotation, -PI/4, PI/4)

I’m guessing you used a RayCast2d that will follow your mouse, you just need to put this in the same func for the look at mouse code, if you have like some sort of automatic turret or something, or one controlled by your keyboard, then do this, (put this in your function obviously):

 var turret_rotation
 
 turret_rotation = $Turret.rotation #the name of your turret node
 turret_rotation = clamp(turret_rotation, -PI/4, PI/4)