Skip to content
GodotComponents
← Back to components
The title “Float Component” over a pattern of Godot's Node icon.

Float Component

Type: General

Makes its parent float gently up and down, like a pickup or a hovering item. Add it as a child of any Node2D or Node3D.

Setup

  1. Add a Node as a child of the object that should float (any Node2D or Node3D).
  2. Attach this script to it and name the node FloatComponent.
  3. Adjust Height and Speed in the Inspector. For 3D, try a height of about 0.2.

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 FloatComponent
extends Node

## Makes its parent float gently up and down, like a pickup or a hovering item.
## Add it as a child of any Node2D or Node3D.

## How far the parent moves up and down (pixels in 2D, meters in 3D).
@export var height: float = 0.3
## How many full up-and-down movements per second.
@export var speed: float = 0.5
## Start at a random point of the movement, so several items don't move in sync.
@export var random_start: bool = true

var _parent: Node
var _start_y: float
var _time: float = 0.0


func _ready() -> void:
	_parent = get_parent()
	if not (_parent is Node2D or _parent is Node3D):
		push_warning("FloatComponent needs a Node2D or Node3D parent.")
		set_process(false)
		return
	_start_y = _parent.position.y
	if random_start:
		_time = randf() / speed


func _process(delta: float) -> void:
	_time += delta
	var offset := sin(_time * speed * TAU) * height
	# In 2D, y grows downwards; in 3D, upwards. Both look the same here.
	_parent.position.y = _start_y + offset


## Stops the movement and puts the parent back where it started.
func stop() -> void:
	set_process(false)
	_parent.position.y = _start_y


## Starts the movement again after stop().
func start() -> void:
	set_process(true)

Usage example

GDScript
$Coin/FloatComponent.stop()   # freeze it, e.g. when the coin is picked up
$Coin/FloatComponent.start()  # make it float again