Change UI-visible names for automated_defense ("Turret") and
slowing_trap ("Tar patch") in StructureSystem.NAMES, plus the
matching upgrade descriptions in game_config.gd/.tres. Internal
dictionary keys/ids are unchanged for save compatibility.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
642 lines
22 KiB
GDScript
642 lines
22 KiB
GDScript
class_name StructureSystem
|
|
extends Node3D
|
|
## Player-built defenses. The records live in FarmState.structures; this system validates and
|
|
## places them, builds their views, keeps the navigation's structure layer in sync, and runs them:
|
|
## fence 2 m segment that ground enemies can't walk through.
|
|
## gate a fence segment the scarecrow walks through (it swings open as the
|
|
## scarecrow nears; it has no collision for the scarecrow) but enemies can't.
|
|
## slowing_trap 1.5 m patch: a ground enemy stepping on it moves at trap_slow_factor speed
|
|
## for trap_slow_time, using up one of its trap_triggers. Doesn't block.
|
|
## automated_defense 1 m post that shoots the nearest enemy within turret_range with a clear
|
|
## line, from the shared shot pool, every turret_fire_interval (leading the
|
|
## target). Flying enemies are hit too (Step 9); fences, gates, and traps
|
|
## don't affect them.
|
|
## Barriers (everything but traps) are high-cost cells for enemy navigation; an enemy whose route
|
|
## runs into one hits it (damage) until it breaks, then carries on. Damaged structures show an HP
|
|
## bar, a red tint, and wobble on each hit; a broken one leaves debris and emits destroyed
|
|
## ("breach"). Positions snap to a 0.5 m grid, rotations to 45 degree steps (fences run 2 m along
|
|
## the grid, 1.5 x 1.5 m on the diagonal, so chains line up either way).
|
|
|
|
signal layout_changed
|
|
signal built(id: int, type: String)
|
|
signal destroyed(id: int, type: String, position: Vector3)
|
|
## Damaged but still standing; repaired fully; an automated defense shot; a trap slowed someone.
|
|
signal hurt(id: int, position: Vector3)
|
|
signal repaired(id: int)
|
|
signal turret_fired(position: Vector3)
|
|
signal trap_sprung(position: Vector3)
|
|
|
|
const PREF := "res://assets/farm/ithappy/farm/prefabs/assets/"
|
|
const ORDER: Array[String] = ["fence", "gate", "slowing_trap", "automated_defense"]
|
|
const NAMES := {
|
|
"fence": "Fence",
|
|
"gate": "Gate",
|
|
"slowing_trap": "Tar patch",
|
|
"automated_defense": "Turret",
|
|
}
|
|
const GRID := 0.5
|
|
const FENCE_LENGTH := 2.0
|
|
const DIAGONAL_FENCE_LENGTH := 2.1213 # 1.5 * sqrt(2)
|
|
const FENCE_THICKNESS := 0.2
|
|
## Clear space kept around each gap in the remaining perimeter fence (the scarecrow's ways out to
|
|
## the gathering areas) and in front of the barn doors.
|
|
const GAP_CLEAR := 2.5
|
|
const DOOR_RECT := Rect2(-0.8, -21.2, 3.6, 3.4)
|
|
const WOBBLE_TIME := 0.35
|
|
|
|
var campaign: CampaignController
|
|
var config: GameConfig
|
|
var nav: FarmNavigation
|
|
var zones: FarmZones
|
|
var enemies: EnemySystem
|
|
var projectiles: FarmProjectiles
|
|
var player: PlayerCharacter
|
|
## Co-op: player 2's scarecrow (gates open for it too, and nothing is built onto it).
|
|
var partner: Node3D
|
|
|
|
var _views := {} # id -> Node3D
|
|
var _bars := {} # id -> MeshInstance3D
|
|
var _bodies := {} # id -> Array[RID] (physics bodies to leave out of placement queries)
|
|
var _tints := {} # id -> StandardMaterial3D
|
|
var _wobble := {} # id -> seconds left
|
|
var _turret_cd := {} # id -> seconds left
|
|
var _heads := {} # id -> Node3D (turret head)
|
|
var _gate_open := {} # id -> 0..1
|
|
var _crop_rects: Array[Rect2] = []
|
|
var _gap_points := PackedVector2Array()
|
|
var _query := PhysicsShapeQueryParameters3D.new()
|
|
var _query_box := BoxShape3D.new()
|
|
var _bar_shader: Shader
|
|
|
|
|
|
func setup(p_campaign: CampaignController, p_nav: FarmNavigation, p_zones: FarmZones, p_enemies: EnemySystem,
|
|
p_projectiles: FarmProjectiles, p_player: PlayerCharacter) -> void:
|
|
campaign = p_campaign
|
|
config = p_campaign.config
|
|
nav = p_nav
|
|
zones = p_zones
|
|
enemies = p_enemies
|
|
projectiles = p_projectiles
|
|
player = p_player
|
|
nav.set_barrier_cost(roundi(config.barrier_detour / nav.cell_size * FarmNavigation.COST_ORTH))
|
|
_bar_shader = load("res://game/resources/hp_bar.gdshader") as Shader
|
|
for u in zones.crop_units():
|
|
var lo := Vector2(INF, INF)
|
|
var hi := Vector2(-INF, -INF)
|
|
for plant in u.get_children():
|
|
var p := Vector2((plant as Node3D).global_position.x, (plant as Node3D).global_position.z)
|
|
lo = lo.min(p)
|
|
hi = hi.max(p)
|
|
_crop_rects.append(Rect2(lo, hi - lo).grow(0.5))
|
|
var map := zones.playable
|
|
for m in zones.gaps():
|
|
var g := Vector2(m.global_position.x, m.global_position.z)
|
|
_gap_points.append(Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y)))
|
|
_query.shape = _query_box
|
|
_query.collision_mask = 1
|
|
_query.collide_with_areas = false
|
|
sync_from_state()
|
|
|
|
|
|
## Full health of a structure type, with upgrades (reinforced fences and gates).
|
|
func max_hp(type: String) -> int:
|
|
var hp := config.structure_hp(type)
|
|
if type == "fence" or type == "gate":
|
|
hp = roundi(hp * Upgrades.value(config, campaign.state, "barrier_hp"))
|
|
return hp
|
|
|
|
|
|
## The automated defense's range and the traps' slow time, with upgrades.
|
|
func turret_range() -> float:
|
|
return Upgrades.value(config, campaign.state, "turret_range")
|
|
|
|
|
|
func trap_slow_time() -> float:
|
|
return Upgrades.value(config, campaign.state, "trap_slow_time")
|
|
|
|
|
|
func blocks(type: String) -> bool:
|
|
return type != "slowing_trap"
|
|
|
|
|
|
func count() -> int:
|
|
return campaign.state.structures.size()
|
|
|
|
|
|
## Snaps a world point onto the build grid.
|
|
static func snap(p: Vector2) -> Vector2:
|
|
return Vector2(roundf(p.x / GRID) * GRID, roundf(p.y / GRID) * GRID)
|
|
|
|
|
|
## Oriented footprint {"center", "half", "angle"} (angle: the long axis from +X toward +Z).
|
|
func footprint(type: String, x: float, z: float, rot: int) -> Dictionary:
|
|
var half := Vector2(0.75, 0.75) if type == "slowing_trap" else Vector2(0.5, 0.5)
|
|
var angle := 0.0
|
|
if type == "fence" or type == "gate":
|
|
half = Vector2((DIAGONAL_FENCE_LENGTH if rot % 2 == 1 else FENCE_LENGTH) * 0.5, FENCE_THICKNESS * 0.5)
|
|
angle = rot * PI / 4.0
|
|
return {"center": Vector2(x, z), "half": half, "angle": angle}
|
|
|
|
|
|
## Closed outline (5 points) of a footprint, optionally shrunk along its length / width.
|
|
static func corners(fp: Dictionary, shrink_long: float = 0.0, shrink_wide: float = 0.0) -> PackedVector2Array:
|
|
var c: Vector2 = fp["center"]
|
|
var h: Vector2 = fp["half"] - Vector2(shrink_long, shrink_wide)
|
|
var u := Vector2(cos(fp["angle"]), sin(fp["angle"]))
|
|
var v := Vector2(-u.y, u.x)
|
|
var pts := PackedVector2Array([c + u * h.x + v * h.y, c - u * h.x + v * h.y, c - u * h.x - v * h.y, c + u * h.x - v * h.y])
|
|
pts.append(pts[0])
|
|
return pts
|
|
|
|
|
|
## Why a structure can't go here ("" if it can). Space first, then daytime, then the cost.
|
|
func validate(type: String, x: float, z: float, rot: int, scarecrow: Vector2) -> String:
|
|
var fp := footprint(type, x, z, rot)
|
|
var outline := corners(fp)
|
|
var inside := zones.playable.grow(-0.3)
|
|
for i in 4:
|
|
if not inside.has_point(outline[i]):
|
|
return "Build inside the farm"
|
|
for g in _gap_points:
|
|
if _distance_to_outline(g, outline) < GAP_CLEAR:
|
|
return "Keep the gap clear"
|
|
if _overlaps_rect(outline, DOOR_RECT):
|
|
return "Keep the barn doors clear"
|
|
for r in _crop_rects:
|
|
if _overlaps_rect(outline, r):
|
|
return "Not on the crops"
|
|
var tight := corners(fp, 0.2, 0.02)
|
|
for e in campaign.state.structures:
|
|
if _overlap(tight, corners(footprint(e["type"], e["x"], e["z"], e["rot"]), 0.2, 0.02)):
|
|
return "Something is built here already"
|
|
if _world_blocked(fp):
|
|
return "Blocked"
|
|
if _distance_to_outline(scarecrow, outline) < 0.45 and blocks(type) and type != "gate":
|
|
return "The scarecrow is in the way"
|
|
if partner != null and blocks(type) and type != "gate" \
|
|
and _distance_to_outline(Vector2(partner.global_position.x, partner.global_position.z), outline) < 0.45:
|
|
return "The other scarecrow is in the way"
|
|
for d in enemies.active_count:
|
|
if enemies.alive[d] == 1 and _distance_to_outline(Vector2(enemies.pos_x[d], enemies.pos_z[d]), outline) < config.enemy_radius:
|
|
return "An enemy is in the way"
|
|
if scarecrow.distance_to(Vector2(x, z)) > config.build_range:
|
|
return "Too far from the scarecrow"
|
|
if not campaign.is_daytime():
|
|
return "Building is for daytime"
|
|
var cost: Dictionary = config.costs.get(type, {})
|
|
if not campaign.state.resources.can_afford(cost):
|
|
return "Not enough: need %s more" % ResourceStore.describe(campaign.state.resources.missing(cost))
|
|
return ""
|
|
|
|
|
|
## Builds after validate() passed: pays, records, shows, and updates navigation. Returns the id.
|
|
func place(type: String, x: float, z: float, rot: int) -> int:
|
|
var s := campaign.state
|
|
if not s.pay(config.costs.get(type, {})):
|
|
return -1
|
|
var id := s.next_structure_id
|
|
s.next_structure_id += 1
|
|
s.structures.append({"id": id, "type": type, "x": x, "z": z, "rot": rot, "hp": max_hp(type)})
|
|
s.record_event("structures_built")
|
|
_add_view(s.structures[s.structures.size() - 1])
|
|
_update_nav()
|
|
built.emit(id, type)
|
|
return id
|
|
|
|
|
|
## Takes a structure down, refunding dismantle_refund of its cost into the shed. Returns the
|
|
## refund.
|
|
func dismantle(id: int) -> Dictionary:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty():
|
|
return {}
|
|
var refund := {}
|
|
var cost: Dictionary = config.costs.get(e["type"], {})
|
|
for m in cost:
|
|
var back := floori(int(cost[m]) * config.dismantle_refund)
|
|
if back > 0:
|
|
refund[m] = back
|
|
campaign.state.resources.shed[m] = int(campaign.state.resources.shed[m]) + back
|
|
_remove(id)
|
|
return refund
|
|
|
|
|
|
## Damages a structure; at 0 HP it breaks (debris, destroyed). Returns true if it broke.
|
|
func damage(id: int, amount: int) -> bool:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty():
|
|
return false
|
|
campaign.state.record_event("structures_damaged", mini(amount, int(e["hp"])))
|
|
e["hp"] = maxi(int(e["hp"]) - amount, 0)
|
|
_wobble[id] = WOBBLE_TIME
|
|
if int(e["hp"]) > 0:
|
|
hurt.emit(id, Vector3(e["x"], 0.0, e["z"]))
|
|
return false
|
|
campaign.state.record_event("structures_destroyed")
|
|
var at := Vector3(e["x"], 0.0, e["z"])
|
|
var type: String = e["type"]
|
|
_debris(at)
|
|
_remove(id)
|
|
destroyed.emit(id, type, at)
|
|
return true
|
|
|
|
|
|
## Co-op partner: the broken bits where a structure fell on the host.
|
|
func show_debris(at: Vector3) -> void:
|
|
_debris(at)
|
|
|
|
|
|
## What a full repair costs now (empty if nothing is missing).
|
|
func repair_cost(id: int) -> Dictionary:
|
|
var e := campaign.state.structure(id)
|
|
if e.is_empty():
|
|
return {}
|
|
var top := max_hp(e["type"])
|
|
var missing := top - int(e["hp"])
|
|
if missing <= 0:
|
|
return {}
|
|
var out := {}
|
|
var cost: Dictionary = config.costs.get(e["type"], {})
|
|
for m in cost:
|
|
out[m] = ceili(int(cost[m]) * missing / float(top))
|
|
return out
|
|
|
|
|
|
## Pays and repairs fully. Returns false if there was nothing to repair or it couldn't be paid.
|
|
func repair(id: int) -> bool:
|
|
var cost := repair_cost(id)
|
|
if cost.is_empty() or not campaign.state.pay(cost):
|
|
return false
|
|
var e := campaign.state.structure(id)
|
|
e["hp"] = max_hp(e["type"])
|
|
campaign.state.record_event("repairs")
|
|
repaired.emit(id)
|
|
return true
|
|
|
|
|
|
## The structure whose footprint is within reach of p, preferring damaged ones, or -1.
|
|
func structure_near(p: Vector2, reach: float, damaged_only: bool = false) -> int:
|
|
var best := -1
|
|
var best_d := INF
|
|
for e in campaign.state.structures:
|
|
if damaged_only and int(e["hp"]) >= max_hp(e["type"]):
|
|
continue
|
|
var d := _distance_to_outline(p, corners(footprint(e["type"], e["x"], e["z"], e["rot"])))
|
|
if d <= reach and d < best_d:
|
|
best = int(e["id"])
|
|
best_d = d
|
|
return best
|
|
|
|
|
|
## A ground enemy at (x, z) steps on a slowing trap with triggers left: uses one up. Returns true
|
|
## if the enemy is slowed.
|
|
func try_trap(x: float, z: float) -> bool:
|
|
for e in campaign.state.structures:
|
|
if e["type"] != "slowing_trap" or int(e["hp"]) <= 0:
|
|
continue
|
|
if absf(x - float(e["x"])) <= 0.75 and absf(z - float(e["z"])) <= 0.75:
|
|
e["hp"] = int(e["hp"]) - 1
|
|
trap_sprung.emit(Vector3(e["x"], 0.0, e["z"]))
|
|
return true
|
|
return false
|
|
|
|
|
|
## Physics tick: the automated defenses shoot.
|
|
func step(dt: float) -> void:
|
|
for e in campaign.state.structures:
|
|
if e["type"] != "automated_defense":
|
|
continue
|
|
var id: int = e["id"]
|
|
var cd := maxf(float(_turret_cd.get(id, 0.0)) - dt, 0.0)
|
|
if cd > 0.0:
|
|
_turret_cd[id] = cd
|
|
continue
|
|
var from := Vector2(e["x"], e["z"])
|
|
var target := -1
|
|
var best := turret_range()
|
|
for d in enemies.active_count:
|
|
if enemies.alive[d] == 0:
|
|
continue
|
|
var p := Vector2(enemies.pos_x[d], enemies.pos_z[d])
|
|
var dist := p.distance_to(from)
|
|
if dist < best and nav.line_clear(from.x, from.y, p.x, p.y, true):
|
|
best = dist
|
|
target = d
|
|
if target < 0:
|
|
_turret_cd[id] = 0.0
|
|
continue
|
|
var lead := best / config.projectile_speed
|
|
var aim := Vector2(enemies.pos_x[target] + enemies.vel_x[target] * lead, enemies.pos_z[target] + enemies.vel_z[target] * lead) - from
|
|
var dir := Vector3(aim.x, 0.0, aim.y).normalized()
|
|
var origin := Vector3(from.x, config.combat_height, from.y)
|
|
projectiles.fire(origin, origin + dir * 0.6, dir)
|
|
turret_fired.emit(origin)
|
|
_turret_cd[id] = config.turret_fire_interval
|
|
var head: Node3D = _heads.get(id)
|
|
if head != null:
|
|
head.rotation.y = atan2(-dir.x, -dir.z)
|
|
|
|
|
|
## Rebuilds every view and the navigation layer from the farm state (new vacation, retry).
|
|
func sync_from_state() -> void:
|
|
for id in _views.keys():
|
|
(_views[id] as Node3D).queue_free()
|
|
_views.clear()
|
|
_bars.clear()
|
|
_bodies.clear()
|
|
_tints.clear()
|
|
_wobble.clear()
|
|
_heads.clear()
|
|
_turret_cd.clear()
|
|
_gate_open.clear()
|
|
for e in campaign.state.structures:
|
|
_add_view(e)
|
|
_update_nav()
|
|
|
|
|
|
## A display-only copy of a structure (no collision), for the build preview.
|
|
func make_ghost(type: String, rot: int) -> Node3D:
|
|
var root := _build_view(type, rot)
|
|
_strip_collision(root)
|
|
return root
|
|
|
|
|
|
func body_rids() -> Array[RID]:
|
|
var out: Array[RID] = []
|
|
for id in _bodies:
|
|
out.append_array(_bodies[id])
|
|
return out
|
|
|
|
|
|
func _process(delta: float) -> void:
|
|
var near := player.global_position if player != null else Vector3(INF, 0.0, INF)
|
|
var near2 := partner.global_position if partner != null else Vector3(INF, 0.0, INF)
|
|
for e in campaign.state.structures:
|
|
var id: int = e["id"]
|
|
var view: Node3D = _views.get(id)
|
|
if view == null:
|
|
continue
|
|
var top := max_hp(e["type"])
|
|
var frac := float(e["hp"]) / float(top)
|
|
var bar: MeshInstance3D = _bars.get(id)
|
|
if bar != null:
|
|
bar.visible = frac < 1.0
|
|
(bar.material_override as ShaderMaterial).set_shader_parameter("fill", frac)
|
|
var tint: StandardMaterial3D = _tints.get(id)
|
|
if tint != null:
|
|
tint.albedo_color.a = (1.0 - frac) * 0.45 if e["type"] != "slowing_trap" else 0.0
|
|
var w := maxf(float(_wobble.get(id, 0.0)) - delta, 0.0)
|
|
_wobble[id] = w
|
|
view.rotation.z = sin(w * 60.0) * 0.08 * (w / WOBBLE_TIME)
|
|
if e["type"] == "slowing_trap":
|
|
view.get_node("Tar").visible = int(e["hp"]) > 0
|
|
elif e["type"] == "gate":
|
|
var dist := minf(Vector2(near.x - float(e["x"]), near.z - float(e["z"])).length(),
|
|
Vector2(near2.x - float(e["x"]), near2.z - float(e["z"])).length())
|
|
var target := 1.0 if dist < 2.2 else 0.0
|
|
var o := move_toward(float(_gate_open.get(id, 0.0)), target, delta * 3.0)
|
|
_gate_open[id] = o
|
|
var panel := view.get_node("Panel") as Node3D
|
|
panel.rotation.y = deg_to_rad(32.5 + 100.0 * o)
|
|
|
|
|
|
func _remove(id: int) -> void:
|
|
var s := campaign.state
|
|
for i in s.structures.size():
|
|
if int(s.structures[i]["id"]) == id:
|
|
s.structures.remove_at(i)
|
|
break
|
|
var view: Node3D = _views.get(id)
|
|
if view != null:
|
|
view.queue_free()
|
|
for d in [_views, _bars, _bodies, _tints, _wobble, _heads, _turret_cd, _gate_open]:
|
|
(d as Dictionary).erase(id)
|
|
_update_nav()
|
|
|
|
|
|
func _update_nav() -> void:
|
|
var entries: Array = []
|
|
for e in campaign.state.structures:
|
|
if blocks(e["type"]):
|
|
entries.append({"id": e["id"], "outline": corners(footprint(e["type"], e["x"], e["z"], e["rot"]))})
|
|
nav.set_structures(entries)
|
|
layout_changed.emit()
|
|
|
|
|
|
func _add_view(e: Dictionary) -> void:
|
|
var id: int = e["id"]
|
|
var view := _build_view(e["type"], e["rot"])
|
|
view.name = "%s_%d" % [e["type"], id]
|
|
add_child(view)
|
|
_views[id] = view
|
|
view.global_position = Vector3(e["x"], _ground_y(Vector2(e["x"], e["z"])), e["z"])
|
|
var rids: Array[RID] = []
|
|
for body in view.find_children("*", "StaticBody3D", true, false):
|
|
rids.append((body as StaticBody3D).get_rid())
|
|
_bodies[id] = rids
|
|
var tint := StandardMaterial3D.new()
|
|
tint.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
|
|
tint.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
|
|
tint.albedo_color = Color(0.9, 0.1, 0.05, 0.0)
|
|
for mi in view.find_children("*", "MeshInstance3D", true, false):
|
|
(mi as MeshInstance3D).material_overlay = tint
|
|
_tints[id] = tint
|
|
var quad := QuadMesh.new()
|
|
quad.size = Vector2(1.1, 0.14)
|
|
var mat := ShaderMaterial.new()
|
|
mat.shader = _bar_shader
|
|
var bar := MeshInstance3D.new()
|
|
bar.mesh = quad
|
|
bar.material_override = mat
|
|
bar.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
|
bar.top_level = true
|
|
bar.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
|
|
bar.visible = false
|
|
view.add_child(bar)
|
|
bar.global_position = view.global_position + Vector3(0.0, 2.3, 0.0)
|
|
_bars[id] = bar
|
|
if e["type"] == "automated_defense":
|
|
_heads[id] = view.get_node("Head")
|
|
|
|
|
|
## The visual (and, for barriers other than gates, collision) of a structure, centered on its
|
|
## footprint and rotated to it.
|
|
func _build_view(type: String, rot: int) -> Node3D:
|
|
var root := Node3D.new()
|
|
root.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
|
|
var fp := footprint(type, 0.0, 0.0, rot)
|
|
root.rotation.y = -float(fp["angle"])
|
|
match type:
|
|
"fence":
|
|
var fence := _instance("prop/fence_026.tscn")
|
|
fence.scale.x = float(fp["half"].x) * 2.0 / 2.08
|
|
fence.position.x = -0.05 * fence.scale.x
|
|
root.add_child(fence)
|
|
"gate":
|
|
var panel := _instance("prop/fence_018.tscn")
|
|
panel.name = "Panel"
|
|
panel.position = Vector3(-0.865, 0.0, 0.0)
|
|
panel.rotation.y = deg_to_rad(32.5)
|
|
_strip_collision(panel) # the scarecrow walks through; enemies are kept out by navigation
|
|
root.add_child(panel)
|
|
for end in [-1.0, 1.0]:
|
|
var post := _instance("prop/fence_027.tscn")
|
|
post.position = Vector3(end * 0.95, 0.0, 0.0)
|
|
root.add_child(post)
|
|
"slowing_trap":
|
|
var tar := MeshInstance3D.new()
|
|
tar.name = "Tar"
|
|
var box := BoxMesh.new()
|
|
box.size = Vector3(1.4, 0.06, 1.4)
|
|
var mat := StandardMaterial3D.new()
|
|
mat.albedo_color = Color(0.1, 0.07, 0.05)
|
|
mat.roughness = 0.2
|
|
mat.metallic_specular = 0.8
|
|
box.material = mat
|
|
tar.mesh = box
|
|
tar.position.y = 0.04
|
|
root.add_child(tar)
|
|
var bucket := _instance("prop/bucket_001.tscn")
|
|
bucket.position = Vector3(0.55, 0.0, 0.55)
|
|
_strip_collision(bucket)
|
|
root.add_child(bucket)
|
|
"automated_defense":
|
|
var base := _instance("prop/barrel_001.tscn")
|
|
root.add_child(base)
|
|
var metal := StandardMaterial3D.new()
|
|
metal.albedo_color = Color(0.25, 0.27, 0.3)
|
|
metal.metallic = 0.6
|
|
var accent := StandardMaterial3D.new()
|
|
accent.albedo_color = Color(0.95, 0.55, 0.15)
|
|
var post := MeshInstance3D.new()
|
|
var cyl := CylinderMesh.new()
|
|
cyl.top_radius = 0.06
|
|
cyl.bottom_radius = 0.06
|
|
cyl.height = 0.55
|
|
cyl.material = metal
|
|
post.mesh = cyl
|
|
post.position.y = 1.2
|
|
root.add_child(post)
|
|
var head := Node3D.new()
|
|
head.name = "Head"
|
|
head.position.y = 1.5
|
|
root.add_child(head)
|
|
var body := MeshInstance3D.new()
|
|
var bm := BoxMesh.new()
|
|
bm.size = Vector3(0.3, 0.22, 0.4)
|
|
bm.material = accent
|
|
body.mesh = bm
|
|
head.add_child(body)
|
|
var gun := MeshInstance3D.new()
|
|
var gm := CylinderMesh.new()
|
|
gm.top_radius = 0.05
|
|
gm.bottom_radius = 0.05
|
|
gm.height = 0.6
|
|
gm.material = metal
|
|
gun.mesh = gm
|
|
gun.rotation.x = PI * 0.5
|
|
gun.position.z = -0.4
|
|
head.add_child(gun)
|
|
return root
|
|
|
|
|
|
func _instance(path: String) -> Node3D:
|
|
return (load(PREF + path) as PackedScene).instantiate() as Node3D
|
|
|
|
|
|
static func _strip_collision(node: Node) -> void:
|
|
for body in node.find_children("*", "CollisionObject3D", true, false):
|
|
(body as CollisionObject3D).collision_layer = 0
|
|
(body as CollisionObject3D).collision_mask = 0
|
|
|
|
|
|
## Height of the ground under p (walkable terrain), for placing views.
|
|
func _ground_y(p: Vector2) -> float:
|
|
if not is_inside_tree():
|
|
return 0.0
|
|
var ray := PhysicsRayQueryParameters3D.create(Vector3(p.x, 5.0, p.y), Vector3(p.x, -2.0, p.y), 1)
|
|
ray.exclude = body_rids()
|
|
var hit := get_world_3d().direct_space_state.intersect_ray(ray)
|
|
return maxf((hit["position"] as Vector3).y, 0.0) if not hit.is_empty() and (hit["position"] as Vector3).y < 1.0 else 0.0
|
|
|
|
|
|
## Anything solid (not walkable terrain, not another structure) under the footprint, with its
|
|
## ends trimmed so a fence may touch a wall or a post.
|
|
func _world_blocked(fp: Dictionary) -> bool:
|
|
var h: Vector2 = fp["half"]
|
|
_query_box.size = Vector3(maxf(h.x * 2.0 - 0.3, 0.1), 1.4, maxf(h.y * 2.0, 0.1))
|
|
var c: Vector2 = fp["center"]
|
|
_query.transform = Transform3D(Basis(Vector3.UP, -float(fp["angle"])), Vector3(c.x, 1.05, c.y))
|
|
_query.exclude = body_rids()
|
|
for hit in get_world_3d().direct_space_state.intersect_shape(_query, 16):
|
|
var body := hit["collider"] as CollisionObject3D
|
|
if body == null:
|
|
continue
|
|
var owner_id := body.shape_find_owner(int(hit["shape"]))
|
|
var cs := body.shape_owner_get_owner(owner_id) as CollisionShape3D
|
|
if cs != null and cs.shape is ConcavePolygonShape3D:
|
|
continue # ground and road tiles
|
|
return true
|
|
return false
|
|
|
|
|
|
func _debris(at: Vector3) -> void:
|
|
var p := CPUParticles3D.new()
|
|
var box := BoxMesh.new()
|
|
box.size = Vector3(0.14, 0.06, 0.3)
|
|
var mat := StandardMaterial3D.new()
|
|
mat.albedo_color = Color(0.45, 0.3, 0.18)
|
|
box.material = mat
|
|
p.mesh = box
|
|
p.amount = 18
|
|
p.lifetime = 1.0
|
|
p.one_shot = true
|
|
p.explosiveness = 1.0
|
|
p.direction = Vector3.UP
|
|
p.spread = 70.0
|
|
p.initial_velocity_min = 2.5
|
|
p.initial_velocity_max = 5.0
|
|
p.angular_velocity_min = -360.0
|
|
p.angular_velocity_max = 360.0
|
|
p.gravity = Vector3(0.0, -12.0, 0.0)
|
|
add_child(p)
|
|
p.global_position = at + Vector3(0.0, 0.8, 0.0)
|
|
p.emitting = true
|
|
get_tree().create_timer(1.5).timeout.connect(p.queue_free)
|
|
|
|
|
|
static func _distance_to_outline(p: Vector2, outline: PackedVector2Array) -> float:
|
|
if Geometry2D.is_point_in_polygon(p, outline):
|
|
return 0.0
|
|
var best := INF
|
|
for k in outline.size() - 1:
|
|
best = minf(best, p.distance_to(Geometry2D.get_closest_point_to_segment(p, outline[k], outline[k + 1])))
|
|
return best
|
|
|
|
|
|
static func _overlaps_rect(outline: PackedVector2Array, r: Rect2) -> bool:
|
|
var box := PackedVector2Array([r.position, Vector2(r.end.x, r.position.y), r.end, Vector2(r.position.x, r.end.y), r.position])
|
|
return _overlap(outline, box)
|
|
|
|
|
|
## Separating-axis test for two closed convex outlines.
|
|
static func _overlap(a: PackedVector2Array, b: PackedVector2Array) -> bool:
|
|
for poly in [a, b]:
|
|
for k in poly.size() - 1:
|
|
var edge: Vector2 = poly[k + 1] - poly[k]
|
|
var axis := Vector2(-edge.y, edge.x)
|
|
var a_lo := INF
|
|
var a_hi := -INF
|
|
var b_lo := INF
|
|
var b_hi := -INF
|
|
for i in a.size() - 1:
|
|
var d := a[i].dot(axis)
|
|
a_lo = minf(a_lo, d)
|
|
a_hi = maxf(a_hi, d)
|
|
for i in b.size() - 1:
|
|
var d := b[i].dot(axis)
|
|
b_lo = minf(b_lo, d)
|
|
b_hi = maxf(b_hi, d)
|
|
if a_hi <= b_lo or b_hi <= a_lo:
|
|
return false
|
|
return true
|