创建单例模式文件

  • 新建一个00_Global文件夹,保证一直都在最上
    • 创建一个GlobalLevelManager脚本文件

      1
      2
      3
      4
      5
      6
      7
      8
      9
      extends Node

      var current_tilemap_bounds: Array[Vector2]

      signal TileMapBoundsChanged(bounds: Array[Vector2])

      func ChangeTileMapBounds(bounds: Array[Vector2]) -> void:
      current_tilemap_bounds = bounds
      TileMapBoundsChanged.emit(bounds)
    • 添加到AutoLoad中

创建Camera2D的脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class_name PlayerCamera extends Camera2D

func _ready() -> void:
LevelManager.TileMapBoundsChanged.connect(UpdateLimits)
UpdateLimits(LevelManager.current_tilemap_bounds)
pass

func UpdateLimits(bounds: Array[Vector2]) -> void:
if bounds == []:
return
limit_left = int (bounds[0].x)
limit_top = int (bounds[0].y)
limit_right = int (bounds[1].x)
limit_bottom = int (bounds[1].y)
pass

为Grass-01创建脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class_name LevelTileMap extends TileMapLayer

func _ready() -> void:
LevelManager.ChangeTileMapBounds(GetTileMapBounds())
pass

func GetTileMapBounds() -> Array[Vector2]:
var bounds: Array[Vector2] = []
bounds.append(
Vector2(get_used_rect().position * rendering_quadrant_size)
)
bounds.append(
Vector2(get_used_rect().end * rendering_quadrant_size)
)
return bounds

总结

  • 场景加载时会更新全局的bounds
  • LevelManager会更新数据并发送信号
  • camera2D接收到信号并更新限制

问题解决

  • 遇到问题camera与tilemap对不上,查到原因是tilemap位置偏差没有在原点