Skip to content

Commit

Permalink
improvement: dampen scrolling when using the touchpad
Browse files Browse the repository at this point in the history
  • Loading branch information
NathanLovato committed Jan 30, 2022
1 parent 748c52d commit 812bda5
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions addons/SmoothScroll/SmoothScrollContainer.gd
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ const SPEED_DISTANCE_DIVISOR := 200.0
# Scroll speed in pixels per second.
var scroll_speed := SPEED_BASE
var arrive_distance := ARRIVE_DISTANCE_BASE
# Multiplier that decreases when scroll events are close in time. Helps to
# make the touchpad and mouse wheel scroll similar.
var damping_factor := 1.0 setget set_damping_factor

# Current velocity of the content node.
var _velocity := Vector2(0, 0)
Expand Down Expand Up @@ -59,7 +62,9 @@ func _process(delta: float) -> void:
set_process(false)
return

var speed_multiplier := max((distance_to_target - ACCELERATE_DISTANCE_THRESHOLD) / SPEED_DISTANCE_DIVISOR, 1.0)
var speed_multiplier := max(
(distance_to_target - ACCELERATE_DISTANCE_THRESHOLD) / SPEED_DISTANCE_DIVISOR, 1.0
)
scroll_speed = SPEED_BASE * speed_multiplier
arrive_distance = ARRIVE_DISTANCE_BASE * speed_multiplier

Expand All @@ -74,6 +79,8 @@ func _process(delta: float) -> void:
_current_scroll += _velocity * delta
scroll_vertical = _current_scroll.y

set_damping_factor(damping_factor + 2.0 * delta)


func _gui_input(event: InputEvent) -> void:
if event.is_action("scroll_up") and event.pressed:
Expand All @@ -91,11 +98,13 @@ func _gui_input(event: InputEvent) -> void:


func scroll_up() -> void:
_set_target_position(_target_position + Vector2.UP * MOUSE_SCROLL_STEP * _scroll_sensitivity)
_set_target_position(_target_position + Vector2.UP * MOUSE_SCROLL_STEP * _scroll_sensitivity * damping_factor)
set_damping_factor(damping_factor - 0.1)


func scroll_down() -> void:
_set_target_position(_target_position + Vector2.DOWN * MOUSE_SCROLL_STEP * _scroll_sensitivity)
_set_target_position(_target_position + Vector2.DOWN * MOUSE_SCROLL_STEP * _scroll_sensitivity * damping_factor)
set_damping_factor(damping_factor - 0.1)


func scroll_page_up() -> void:
Expand All @@ -114,6 +123,10 @@ func scroll_to_bottom() -> void:
_set_target_position(Vector2.DOWN * _max_position_y)


func set_damping_factor(new_value: float) -> void:
damping_factor = clamp(new_value, 0.4, 1.0)


func _set_target_position(new_position: Vector2) -> void:
_target_position = new_position
_target_position.y = clamp(_target_position.y, 0.0, _max_position_y)
Expand Down

0 comments on commit 812bda5

Please sign in to comment.