summaryrefslogtreecommitdiff
path: root/scripts/camera.gd
blob: 9c04d29dfb4da62f1f0edba514e463cb868f2c97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
extends Camera2D

@onready var basketball = $"../Basketball"
@onready var hoop = $"../Hoop"

func _ready():
	var bg = $"../Background/Court"
	limit_right = bg.get_rect().size.x + bg.get_rect().position.x + bg.position.x
	limit_left = -bg.get_rect().size.x - bg.get_rect().position.x + bg.position.x
	limit_bottom = bg.get_rect().size.y + bg.get_rect().position.y + bg.position.y
	limit_top = -bg.get_rect().size.y - bg.get_rect().position.y + bg.position.y

func _process(_delta):
	if !basketball.waiting_for_shoot:
		position = (basketball.position + hoop.position) / 2
		adjust_zoom()

func adjust_zoom():
	var dist_to_hoop = basketball.position.distance_to(hoop.position)
	if basketball.waiting_for_shoot:
		dist_to_hoop = basketball.start_position.distance_to(hoop.position)

	# Min and max widths of the court we want visible on screen at once
	var min_width = dist_to_hoop + basketball.drag_radius * 3
	var max_width = limit_right - limit_left
	
	var zoom_level = Vector2(1, 1)

	# Zoom out the camera if we need to show more on screen
	if min_width > limit_right:
		zoom_level /= (min_width / limit_right)

	# Width of the view when the zoom is set to 1
	var view_width = get_viewport().get_visible_rect().size.x

	# Fit the zoom level within the max width if needed
	# TODO: There should also be a vertical limit
	var max_zoom = float(view_width) / float(max_width)
	zoom_level.x = clamp(zoom_level.x, max_zoom, 1)
	zoom_level.y = clamp(zoom_level.y, max_zoom, 1)
	
	set_zoom(zoom_level)

func _on_Basketball_reset():
	position = (basketball.start_position + hoop.position) / 2
	adjust_zoom()