## Cradle — rocks with a pendulum rotation when tapped.
class_name Cradle extends Node2D

enum State { IDLE, ROCKING }

const ROCK_ANGLE: float = 15.0
const ROCK_DURATION: float = 0.5
const BUTTON_HALF_SIZE: float = 80.0

var _state: State = State.IDLE


func _input(event: InputEvent) -> void:
	if _state != State.IDLE:
		return
	var screen_pos: Vector2
	if event is InputEventScreenTouch and event.pressed:
		screen_pos = event.position
	elif event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		screen_pos = event.position
	else:
		return
	var canvas_transform: Transform2D = get_viewport().get_canvas_transform()
	var world_pos: Vector2 = canvas_transform.affine_inverse() * screen_pos
	var local_pos: Vector2 = to_local(world_pos)
	if abs(local_pos.x) <= BUTTON_HALF_SIZE and abs(local_pos.y) <= BUTTON_HALF_SIZE:
		_start_rocking()


func _start_rocking() -> void:
	_state = State.ROCKING
	var tween: Tween = create_tween()
	tween.set_ease(Tween.EASE_IN_OUT)
	tween.set_trans(Tween.TRANS_SINE)
	tween.tween_property(self, "rotation_degrees", ROCK_ANGLE, ROCK_DURATION)
	tween.tween_property(self, "rotation_degrees", -ROCK_ANGLE, ROCK_DURATION)
	tween.tween_property(self, "rotation_degrees", 0.0, ROCK_DURATION * 0.5)
	tween.finished.connect(func() -> void: _state = State.IDLE)
