Need help with designing UI Sway

Godot Version

4.0

Question

I need help designing a UI sway on Godot. I can’t find any tutorials about it anywhere, so i decided to repurpose another script that sways weapons instead. Only problem is that it doesn’t work either. I don’t know what else I can do to achieve the effect I’m looking for.

repurposed code:

extends Control

var mouseMov
var Sway_Threshold = 5
var Sway_Lerp = 5

@export var Sway_Left : Vector2
@export var Sway_Right : Vector2
@export var Sway_Normal : Vector2

func _ready() -> void:
	Sway_Normal = position

func  _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		mouseMov = -event.position.x

func _process(delta: float) -> void:
	if mouseMov !=null:
		if mouseMov > Sway_Threshold:
			position = position.lerp(Sway_Left, Sway_Lerp * delta)
		elif mouseMov < -Sway_Threshold:
			position = position.lerp(Sway_Right, Sway_Lerp * delta)
		else:
			position = position.lerp(Sway_Normal, Sway_Lerp * delta)

What do you actually want this to do?

always static cast your variables, not only does it make the code faster, it makes it easier for us (and godot) to tell what it’s supposed to do, and helps intellisense recommend methods and variables and even stringname parameters.

this is redundant, sway_normal is exported, you are overriding it so it has no reason to be exported.

don’t do this… I can’t… this isn’t C# where a float can be null, I can’t even think of a reason for it.
a float must be either 0, or positive, or negative. so don’t do this check and instead just give mouseMov a type and default value.

controls are meant to follow anchoring, that way they can adapt to the parent or child Controls and that makes our work easier.
position should still work, but you have to make sure the parent of this Node is not a container, otherwise the position will be overridden.

also, read the docs on event.relative:

make sure the stretch mode in project settings is set correctly, and the mouse mode, as that can change what this returns.
you are comparing it to a value of 5, this could be bigger than the screen if it’s on a -1/1 range, or not big enough.

Code makes sense to me. position should move in one direction depending on your mouse movement.

I think you want to use event.relative like the other commenter suggested, otherwise this will only work in the corner of the window or something.

I would add print for the mouseMov variable and each mouseMov if/else case, and export the threshold and lerp as floats, then test.