Spin Component
Type: GeneralMakes its parent spin around an axis, like a coin, a pickup or a fan. Add it as a child of any Node3D or Node2D.
Setup
- Add a Node as a child of the object that should spin (any Node3D or Node2D).
- Attach this script to it and name the node SpinComponent.
- Pick the Axis and Speed in the Inspector. Y spins around the vertical axis.
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 SpinComponent
extends Node
## Makes its parent spin around an axis, like a coin, a pickup or a fan.
## Add it as a child of any Node3D or Node2D.
enum Axis { X, Y, Z }
## The axis to spin around in 3D. Y is the vertical one.
## In 2D the parent always turns in its own plane.
@export var axis: Axis = Axis.Y
## Full turns per second. A negative value spins the other way.
@export var speed: float = 0.5
## Spin around the parent's own axis (on) or the world's axis (off). 3D only.
@export var use_local_axis: bool = true
var _parent: Node
func _ready() -> void:
_parent = get_parent()
if not (_parent is Node2D or _parent is Node3D):
push_warning("SpinComponent needs a Node2D or Node3D parent.")
set_process(false)
func _process(delta: float) -> void:
var angle := speed * TAU * delta
if _parent is Node3D:
var direction: Vector3 = [Vector3.RIGHT, Vector3.UP, Vector3.BACK][axis]
if use_local_axis:
_parent.rotate_object_local(direction, angle)
else:
_parent.rotate(direction, angle)
else:
_parent.rotate(angle)
## Stops the spin where it is.
func stop() -> void:
set_process(false)
## Starts spinning again after stop().
func start() -> void:
set_process(true)Usage example
GDScript
$Coin/SpinComponent.speed = 2.0 # spin faster, e.g. while the coin is being collected
$Coin/SpinComponent.stop() # freeze it in place