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)
