Skip to content
GodotComponents
← Back to components

Parameter Oscillator

Type: General

Oscillates a parameter on a selected node based on a designer-definable curve.

Setup

  1. Add a node with this script anywhere within the tree (As a child of the target is recommended for cleanliness)
  2. Select your target node
  3. Enter a property path (Can be found by going to the target node, right clicking the parameter and clicking "copy property path"
  4. Set the min and max values to the correct variable type (click the little pencil icon next to them)
  5. Set the min and max values
  6. Configure any other parameters. Hover each of them for a description.

Code

Released under CC0 1.0 licence (opens in a new tab): use, change and share it in any project, without asking and without giving credit.

GDScript
class_name ParameterOscillator
extends Node
## Animates a number, vector or color property on any node along a curve.
## Set target_node, property_path (e.g. "position:y" or "modulate:a"),
## min_val / max_val, and optionally a curve.

@export var target_node: Node
@export var property_path: String = "position:x"
@export var min_val: Variant
@export var max_val: Variant
## Shape of the motion. Defaults to a smooth hill (0 -> 1 -> 0).
@export var curve: Curve
## Cycles per second. Negative plays in reverse.
@export var speed: float = 0.5
## Adds an offset to the input time for this oscillation.
@export_range(0.0, 1.0, 0.01) var phase_offset: float = 0.0
## Play forward then backward instead of jumping back to the start.
@export var ping_pong: bool = false
## Add min/max to the property's starting value instead of using them as-is.
@export var relative: bool = false

var _t: float
var _dir: float = 1.0
var _start: Variant
var _path: NodePath


func _ready() -> void:
	if curve == null:
		curve = Curve.new()
		curve.add_point(Vector2(0.0, 0.0), 0.0, 0.0)
		curve.add_point(Vector2(0.5, 1.0), 0.0, 0.0)
		curve.add_point(Vector2(1.0, 0.0), 0.0, 0.0)
	_path = NodePath(property_path.replace(".", ":"))
	_t = phase_offset
	if is_instance_valid(target_node):
		_start = target_node.get_indexed(_path)


func _process(delta: float) -> void:
	if not is_instance_valid(target_node):
		return

	_t += delta * speed * _dir
	if ping_pong:
		if _t > 1.0 or _t < 0.0:
			_dir = -_dir
			_t = clampf(_t, 0.0, 1.0)
	else:
		_t = wrapf(_t, 0.0, 1.0)

	var value: Variant = lerp(min_val, max_val, curve.sample_baked(_t))
	if relative:
		value = _start + value
	if typeof(_start) == TYPE_INT:
		value = roundi(value)
	target_node.set_indexed(_path, value)