ChunkSystem.gd 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 = 1
  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 = Common.posToChunkPos(playerSpos)
  16. var playerInterChunkPos = Vector2(playerSpos.x - playerChunkPos.x, playerSpos.y - playerChunkPos.y)
  17. add_chunk(playerChunkPos)
  18. for lon in range(playerChunkPos.y-renderDistance, playerChunkPos.y+renderDistance):
  19. for lat in range(playerChunkPos.x-renderDistance, playerChunkPos.x+renderDistance):
  20. if not (chunkIndex.has(lon) and chunkIndex[lon].has(lat)):
  21. add_chunk(Vector2(lat,lon))
  22. for lon in chunkIndex:
  23. for lat in chunkIndex[lon]:
  24. if playerChunkPos.distance_to(Vector2(lat,lon)) > renderDistance*3:
  25. remove_chunk(Vector2(lat,lon))
  26. #var dir = Vector2()
  27. #if playerInterChunkPos.x < renderDistance:
  28. # dir = dir+Vector2(-1,0)
  29. #elif playerInterChunkPos.x > 1-renderDistance:
  30. # dir = dir+Vector2(1,0)
  31. #if playerInterChunkPos.y < renderDistance:
  32. # dir = dir+Vector2(0,-1)
  33. #elif playerInterChunkPos.y > 1-renderDistance:
  34. # dir = dir+Vector2(0,1)
  35. #add_chunk(playerChunkPos+dir)
  36. #add_chunk(playerChunkPos+Vector2(0,dir.y))
  37. #add_chunk(playerChunkPos+Vector2(dir.x,0))
  38. #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)]:
  39. # var dist = Vector2(playerSpos.x, playerSpos.y).distance_to(playerChunkPos+i)
  40. # if dist < renderDistance:
  41. # add_chunk(playerChunkPos+i)
  42. func add_chunk(chunkPos = Vector2()):
  43. var lat = int(chunkPos.x)
  44. var lon = int(chunkPos.y)
  45. if chunkIndex.has(lon) and chunkIndex[lon].has(lat):
  46. return
  47. var chunk = Chunk.instance()
  48. chunk.setParams(lat,lat+1,lon,lon+1,resolution,radius,scaleFact)
  49. #moontile.scale=Vector3(1000,1000,1000)
  50. .add_child(chunk)
  51. if not chunkIndex.has(lon):
  52. chunkIndex[lon]={}
  53. chunkIndex[lon][lat] = chunk
  54. func remove_chunk(chunkPos = Vector2()):
  55. print("removing chunk %s" %chunkPos)
  56. var lat = int(chunkPos.x)
  57. var lon = int(chunkPos.y)
  58. if chunkIndex.has(lon) and chunkIndex[lon].has(lat):
  59. chunkIndex[lon][lat].queue_free()
  60. chunkIndex[lon].erase(lat)
  61. if len(chunkIndex[lon]) == 0 :
  62. chunkIndex.erase(lon)