extends KinematicBody2D

export var TimeToCollapse = 1.0;
# Declare member variables here. Examples:
# var a = 2
# var b = "text"
export var gravity = 200;
export var terminal_velocity = 230
export var do_match_speed_factor = 1.1;
var vert_speed = 0;
var is_falling = false;
var has_landed = false;
var am_stopped = false;
var start_shape_position = Vector2(0,0);

func landed():
	if !has_landed:
		has_landed = true
		$Timer.start(TimeToCollapse);

func match_down_speed():
	if am_stopped:
		return 0;
	else:
		return vert_speed*do_match_speed_factor;

func kill():
	if ( is_falling ):
		get_node("/root/Global").playblockdestroy();
		queue_free()

# Called when the node enters the scene tree for the first time.
func _ready():
	$Timer.connect("timeout", self, "fall")
	set_process(true)
	set_physics_process(true)
	start_shape_position = $Shape.position;
	pass # Replace with function body.

func fall():
	is_falling = true;
	$Shape.position = start_shape_position #reset shaking.

func get_is_falling():
	return is_falling;

func _process(delta):
	if has_landed && !is_falling:
		var shake_offset = 10*sin(($Timer.time_left / TimeToCollapse)*6.28*2)
		$Shape.position = Vector2( start_shape_position.x + shake_offset, start_shape_position.y )
		

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
	if is_falling:
		vert_speed += delta*gravity;
		if vert_speed > terminal_velocity:
			vert_speed = terminal_velocity;
	if ( vert_speed != 0 ):
		var old_position = position
		var altered_vector = move_and_slide( Vector2( 0, vert_speed ));
		if abs(old_position.y - position.y) <= 0.02:
			am_stopped = true;
		else:
			am_stopped = false;
	pass
