1
0

block.gd 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. class_name Block
  2. extends AnimatableBody2D
  3. ## One arc-shaped segment of a ring around the core. Its [enum Kind] decides how it looks,
  4. ## how many hits it takes and what it does to the ball.
  5. ## Emitted when a TNT segment breaks; the rings turn it into an explosion.
  6. signal detonated(block: Block)
  7. enum Kind { NORMAL, INDESTRUCTIBLE, WATER, ICE, TNT, RUBBER, GHOST, MOSS, MAGNET }
  8. ## What [method strike] did, so the game can pick a sound.
  9. enum Hit { BROKE, DAMAGED, BLOCKED }
  10. const GAP := 4.0 # px between neighbouring tiles
  11. const CORNER := 4.0 # corner rounding radius in px
  12. const BREAK_SECONDS := 0.15 # fade-out time, after a short flash
  13. ## Per kind: first level it can appear, hits to break (0 = unbreakable) and flat colour.
  14. ## Normal segments get a random blue-green colour instead.
  15. const KINDS := {
  16. Kind.NORMAL: { unlock = 0, hp = 1, color = Params.COLOR_BLUE },
  17. Kind.INDESTRUCTIBLE: { unlock = 0, hp = 0, color = Params.COLOR_ORANGE },
  18. Kind.WATER: { unlock = 50, hp = 3, color = Color("#3a7bff") },
  19. Kind.ICE: { unlock = 100, hp = 2, color = Color("#d6f3ff") },
  20. Kind.TNT: { unlock = 150, hp = 1, color = Params.COLOR_PINK },
  21. Kind.RUBBER: { unlock = 200, hp = 2, color = Color("#ae81ff") },
  22. Kind.GHOST: { unlock = 250, hp = 1, color = Color("#c8c3d8") },
  23. Kind.MOSS: { unlock = 300, hp = 1, color = Params.COLOR_GREEN },
  24. Kind.MAGNET: { unlock = 350, hp = 2, color = Color("#9aa4ad") },
  25. }
  26. const WATER_STICK_SECONDS := 0.35
  27. const WATER_SLOWDOWN := 0.85
  28. const ICE_SPEEDUP := 1.08
  29. const RUBBER_SPEEDUP := 1.15
  30. const GHOST_SOLID_SECONDS := 2.0
  31. const GHOST_PHASED_SECONDS := 1.2
  32. const MOSS_REGROW_SECONDS := 8.0 # moss grows back once, this long after breaking
  33. const MAGNET_RADIUS := 150.0
  34. const MAGNET_PULL := 700.0 # px/s² at the segment, fading to 0 at MAGNET_RADIUS
  35. var kind := Kind.NORMAL
  36. var hp := 1
  37. var color := Params.COLOR_BLUE
  38. var _inner := 0.0
  39. var _outer := 0.0
  40. var _begin := 0.0
  41. var _end := 0.0
  42. var _polygon := PackedVector2Array()
  43. var _collision := CollisionPolygon2D.new()
  44. var _cracks := PackedVector2Array()
  45. var _ghost_clock := 0.0
  46. var _regrown := false
  47. ## 0 to 1: how far the tile is washed towards white while breaking.
  48. var _flash := 0.0:
  49. set(value):
  50. _flash = value
  51. queue_redraw()
  52. func _init(inner: float, outer: float, begin: float, end: float, segment_kind: Kind) -> void:
  53. sync_to_physics = false
  54. collision_layer = Params.LAYER_BLOCKS
  55. collision_mask = 0
  56. _inner = inner
  57. _outer = outer
  58. _begin = begin
  59. _end = end
  60. add_child(_collision)
  61. set_kind(segment_kind)
  62. _ghost_clock = randf() * (GHOST_SOLID_SECONDS + GHOST_PHASED_SECONDS)
  63. func set_kind(value: Kind) -> void:
  64. kind = value
  65. hp = KINDS[kind].hp
  66. if kind == Kind.NORMAL:
  67. color = Color8(
  68. int(102 * (randf() / 5.0 + 0.5)),
  69. int(217 * (randf() / 5.0 + 0.5)),
  70. int(239 * (randf() / 5.0 + 0.5)))
  71. else:
  72. color = KINDS[kind].color
  73. _rebuild_shape()
  74. set_physics_process(kind == Kind.GHOST or kind == Kind.MAGNET)
  75. func is_breakable() -> bool:
  76. return hp > 0
  77. ## Centre of the segment in global coordinates.
  78. func center() -> Vector2:
  79. var middle := (_begin + _end) / 2.0
  80. return to_global(Vector2(sin(middle), cos(middle)) * (_inner + _outer) / 2.0)
  81. ## A ball hit the segment. Applies the segment's effect on the ball and takes a hit.
  82. func strike(ball: Ball) -> Hit:
  83. if not is_breakable():
  84. if ball.superball:
  85. ball.superball = false
  86. destroy()
  87. return Hit.BROKE
  88. return Hit.BLOCKED
  89. if ball.fire:
  90. # Fire burns straight through whatever the segment is.
  91. hp = 1
  92. return damage()
  93. match kind:
  94. Kind.ICE:
  95. ball.velocity *= ICE_SPEEDUP
  96. Kind.RUBBER:
  97. ball.velocity *= RUBBER_SPEEDUP
  98. var result := damage()
  99. if kind == Kind.WATER and result == Hit.DAMAGED:
  100. ball.stick_to(self, WATER_STICK_SECONDS, WATER_SLOWDOWN)
  101. return result
  102. ## Takes one hit from anything (ball, laser, explosion). Unbreakable segments ignore it.
  103. func damage() -> Hit:
  104. if not is_breakable() or collision_layer == 0:
  105. return Hit.BLOCKED
  106. hp -= 1
  107. if hp > 0:
  108. _rebuild_shape()
  109. return Hit.DAMAGED
  110. destroy()
  111. return Hit.BROKE
  112. ## Flashes and fades out. Stops colliding right away. Moss comes back once, after a while.
  113. func destroy() -> void:
  114. collision_layer = 0
  115. if kind == Kind.TNT:
  116. detonated.emit(self)
  117. var tween := create_tween()
  118. tween.tween_property(self, "_flash", 0.8, BREAK_SECONDS / 3.0)
  119. tween.tween_property(self, "modulate:a", 0.0, BREAK_SECONDS)
  120. tween.parallel().tween_property(self, "scale", Vector2.ONE * 1.04, BREAK_SECONDS)
  121. if kind == Kind.MOSS and not _regrown:
  122. tween.tween_interval(MOSS_REGROW_SECONDS)
  123. tween.tween_callback(_regrow)
  124. else:
  125. tween.tween_callback(queue_free)
  126. func _regrow() -> void:
  127. _regrown = true
  128. hp = KINDS[kind].hp
  129. _flash = 0.0
  130. scale = Vector2.ONE * 0.6
  131. var tween := create_tween().set_parallel()
  132. tween.tween_property(self, "modulate:a", 1.0, 0.4)
  133. tween.tween_property(self, "scale", Vector2.ONE, 0.4)
  134. tween.chain().tween_callback(set.bind("collision_layer", Params.LAYER_BLOCKS))
  135. func _physics_process(delta: float) -> void:
  136. if kind == Kind.GHOST and hp > 0:
  137. _ghost_clock = fmod(_ghost_clock + delta, GHOST_SOLID_SECONDS + GHOST_PHASED_SECONDS)
  138. var solid := _ghost_clock < GHOST_SOLID_SECONDS
  139. collision_layer = Params.LAYER_BLOCKS if solid else 0
  140. modulate.a = 1.0 if solid else 0.2
  141. elif kind == Kind.MAGNET and collision_layer != 0:
  142. var here := center()
  143. for ball: Ball in get_tree().get_nodes_in_group("balls"):
  144. var offset := here - ball.global_position
  145. var dist := offset.length()
  146. if dist > 0.0 and dist < MAGNET_RADIUS:
  147. ball.velocity += offset / dist * MAGNET_PULL * (1.0 - dist / MAGNET_RADIUS) * delta
  148. ## Recomputes the drawn and collision outline. Water drains from the outside in as it is hit;
  149. ## ice gets cracks; other multi-hit segments darken.
  150. func _rebuild_shape() -> void:
  151. var outer := _outer
  152. var max_hp: int = KINDS[kind].hp
  153. if kind == Kind.WATER and hp < max_hp:
  154. outer = _inner + (_outer - _inner) * float(hp) / max_hp
  155. _polygon = _round_corners(_sector(_inner + GAP / 2.0, outer - GAP / 2.0, _begin, _end, GAP / 2.0))
  156. # Very short segments can leave a sliver too thin to split into convex pieces; skip its
  157. # collision rather than let Godot fail on it.
  158. var valid := not Geometry2D.decompose_polygon_in_convex(_polygon).is_empty()
  159. _collision.set_deferred("polygon", _polygon if valid else PackedVector2Array())
  160. _collision.set_deferred("disabled", not valid)
  161. _cracks = PackedVector2Array()
  162. if kind == Kind.ICE and hp < max_hp:
  163. _cracks = _crack_lines()
  164. queue_redraw()
  165. func _crack_lines() -> PackedVector2Array:
  166. var lines := PackedVector2Array()
  167. var middle := (_begin + _end) / 2.0
  168. var radius := (_inner + _outer) / 2.0
  169. var start := Vector2(sin(middle), cos(middle)) * radius
  170. for i in 3:
  171. var angle := middle + randf_range(-0.6, 0.6) * (_end - _begin) / 2.0
  172. var r := lerpf(_inner + GAP, _outer - GAP, randf())
  173. lines.append(start)
  174. lines.append(Vector2(sin(angle), cos(angle)) * r)
  175. return lines
  176. func _draw() -> void:
  177. if _polygon.size() < 3:
  178. return # segment too short to show at all
  179. var fill := color
  180. if hp > 0 and hp < KINDS[kind].hp and kind != Kind.WATER and kind != Kind.ICE:
  181. fill = fill.darkened(0.25)
  182. fill = fill.lerp(Color.WHITE, _flash)
  183. draw_colored_polygon(_polygon, fill)
  184. # Polygons have no antialiasing of their own; a smooth outline softens the edge.
  185. var outline := _polygon.duplicate()
  186. outline.append(_polygon[0])
  187. draw_polyline(outline, fill, 1.0, true)
  188. if not _cracks.is_empty():
  189. draw_multiline(_cracks, Color(0.2, 0.35, 0.45, 0.9), 1.5, true)
  190. ## Ring segment between two radii. [param gap] trims each side by that many pixels,
  191. ## so the space between neighbours has the same width at every radius. An edge too short
  192. ## to trim collapses to a point, turning the segment into a wedge.
  193. static func _sector(inner: float, outer: float, begin: float, end: float, gap: float) -> PackedVector2Array:
  194. var steps := maxi(2, int((end - begin) * sqrt(outer) / 1.5))
  195. return _trimmed_arc(outer, begin, end, gap, steps) + _trimmed_arc(inner, end, begin, -gap, steps)
  196. static func _trimmed_arc(radius: float, from: float, to: float, gap: float, steps: int) -> PackedVector2Array:
  197. var trim := gap / radius
  198. if (to - from - 2.0 * trim) * signf(to - from) <= 0.0:
  199. var middle := (from + to) / 2.0
  200. return PackedVector2Array([Vector2(sin(middle), cos(middle)) * radius])
  201. return _arc(radius, from + trim, to - trim, steps)
  202. ## Shrinks then regrows the polygon with round joins, which rounds its corners.
  203. static func _round_corners(polygon: PackedVector2Array) -> PackedVector2Array:
  204. var shrunk := Geometry2D.offset_polygon(polygon, -CORNER)
  205. if shrunk.is_empty():
  206. return polygon
  207. var rounded := Geometry2D.offset_polygon(shrunk[0], CORNER, Geometry2D.JOIN_ROUND)
  208. return polygon if rounded.is_empty() else _without_duplicates(rounded[0])
  209. ## offset_polygon can emit repeated points; zero-length edges break convex decomposition.
  210. static func _without_duplicates(polygon: PackedVector2Array) -> PackedVector2Array:
  211. var result := PackedVector2Array()
  212. for point in polygon:
  213. if result.is_empty() or not point.is_equal_approx(result[-1]):
  214. result.append(point)
  215. if result.size() > 1 and result[0].is_equal_approx(result[-1]):
  216. result.remove_at(result.size() - 1)
  217. return result
  218. static func _arc(radius: float, from: float, to: float, steps: int) -> PackedVector2Array:
  219. var points := PackedVector2Array()
  220. for i in steps + 1:
  221. var angle := lerpf(from, to, float(i) / steps)
  222. points.append(Vector2(sin(angle), cos(angle)) * radius)
  223. return points