Jelajahi Sumber

Improve camera focus and zoom algorithm

Use rect center instead of mass center.
DricomDragon 3 tahun lalu
induk
melakukan
a79f6b0205
1 mengubah file dengan 26 tambahan dan 17 penghapusan
  1. 26 17
      godot/Scripts/MainCamera.gd

+ 26 - 17
godot/Scripts/MainCamera.gd

@@ -36,23 +36,32 @@ func move():
 		center_on(running)
 
 
-func center_on(players):
-	var position_accumulator = Vector2(0.0, 0.0)
-	for p in players:
-		position_accumulator += p.position
-
-	position = position_accumulator / players.size()
-
-	# Compute axis aligned distances
-	var dist_x = 0
-	var dist_y = 0
-	for i in range(players.size() - 1):
-		for j in range(i + 1, players.size()):
-			dist_x = max(dist_x, abs(players[i].position.x - players[j].position.x))
-			dist_y = max(dist_y, abs(players[i].position.y - players[j].position.y))
-
-	# Extend camera zoom if liners are far from each other
-	var new_zoom = 1.0
+func center_on(focus_points: Array) -> void:
+
+	# Focus middle point
+	var last_point: Node2D = focus_points.pop_back()
+	var position_min: Vector2
+
+	if last_point:
+		position_min = last_point.position
+	else:
+		position_min = Vector2(0.0, 0.0)
+
+	var position_max := position_min
+
+	for p in focus_points:
+		position_min.x = min(p.position.x, position_min.x)
+		position_min.y = min(p.position.y, position_min.y)
+		position_max.x = max(p.position.x, position_max.x)
+		position_max.y = max(p.position.y, position_max.y)
+
+	position = (position_min + position_max) / 2
+
+	# Extend camera zoom if focus points are far from each other
+	var dist_x: float = position_max.x - position_min.x
+	var dist_y: float = position_max.y - position_min.y
+
+	var new_zoom: float = 1.0
 	if dist_x > dist_max_x:
 		new_zoom += (dist_x - dist_max_x) * zoom_rate
 	if dist_y > dist_max_y: