ChunkSystem.gd 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. extends Spatial
  2. var Chunk = preload("res://chunk.tscn")
  3. onready var Player = $"../Player"
  4. var resolution = 512
  5. var scaleFact = 1000
  6. var radius = 1737.4*scaleFact
  7. var renderDistance = 3
  8. var chunkIndex = {}
  9. # Called when the node enters the scene tree for the first time.
  10. func _ready():
  11. pass # Replace with function body.
  12. # Called every frame. 'delta' is the elapsed time since the previous frame.
  13. func _process(delta):
  14. var playerSpos = Player.getSpos()
  15. var playerChunkPos = posToChunPos(playerSpos)
  16. var playerInterChunkPos = Vector2(playerSpos.x - playerChunkPos.x, playerSpos.y - playerChunkPos.y)
  17. for lon in range(playerChunkPos.y-renderDistance, playerChunkPos.y+renderDistance):
  18. for lat in range(playerChunkPos.x-renderDistance, playerChunkPos.x+renderDistance):
  19. if not (chunkIndex.has(lon) and chunkIndex[lon].has(lat)):
  20. add_chunk(Vector2(lat,lon))
  21. for lon in chunkIndex:
  22. for lat in chunkIndex[lon]:
  23. if playerChunkPos.distance_to(Vector2(lat,lon)) > renderDistance*3:
  24. remove_chunk(Vector2(lat,lon))
  25. #var dir = Vector2()
  26. #if playerInterChunkPos.x < renderDistance:
  27. # dir = dir+Vector2(-1,0)
  28. #elif playerInterChunkPos.x > 1-renderDistance:
  29. # dir = dir+Vector2(1,0)
  30. #if playerInterChunkPos.y < renderDistance:
  31. # dir = dir+Vector2(0,-1)
  32. #elif playerInterChunkPos.y > 1-renderDistance:
  33. # dir = dir+Vector2(0,1)
  34. #add_chunk(playerChunkPos+dir)
  35. #add_chunk(playerChunkPos+Vector2(0,dir.y))
  36. #add_chunk(playerChunkPos+Vector2(dir.x,0))
  37. #for i in [Vector2(1,0),Vector2(1,1),Vector2(0,1),Vector2(-1,0),Vector2(0,-1),Vector2(-1,-1),Vector2(1,-1),Vector2(-1,1)]:
  38. # var dist = Vector2(playerSpos.x, playerSpos.y).distance_to(playerChunkPos+i)
  39. # if dist < renderDistance:
  40. # add_chunk(playerChunkPos+i)
  41. func posToChunPos(pos):
  42. return Vector2(int(pos.x), int(pos.y))
  43. func add_chunk(chunkPos = Vector2()):
  44. var lat = int(chunkPos.x)
  45. var lon = int(chunkPos.y)
  46. if chunkIndex.has(lon) and chunkIndex[lon].has(lat):
  47. return
  48. var chunk = Chunk.instance()
  49. chunk.setParams(lat,lat+1,lon,lon+1,resolution,radius,scaleFact)
  50. #moontile.scale=Vector3(1000,1000,1000)
  51. .add_child(chunk)
  52. if not chunkIndex.has(lon):
  53. chunkIndex[lon]={}
  54. chunkIndex[lon][lat] = chunk
  55. func remove_chunk(chunkPos = Vector2()):
  56. print("removing chunk %s" %chunkPos)
  57. var lat = int(chunkPos.x)
  58. var lon = int(chunkPos.y)
  59. if chunkIndex.has(lon) and chunkIndex[lon].has(lat):
  60. chunkIndex[lon][lat].queue_free()
  61. chunkIndex[lon].erase(lat)
  62. if len(chunkIndex[lon]) == 0 :
  63. chunkIndex.erase(lon)