harvest/game/scripts/scarecrow_combat.gd
2026-10-04 17:30:48 -04:00

514 lines
19 KiB
GDScript

class_name ScarecrowCombat
extends Node3D
## The scarecrow's weapons, ported from the prototype's PlayerInput + WeaponController (Step 4
## finished the kit; the weapons came after Step 11):
## * Three weapons (Weapon) in two slots: the main weapon in the right hand, the pitchfork
## (every scarecrow's from the start) or the corn shooter, and pumpkin bombs in the off-hand
## (the left); the corn shooter and the bombs are bought at the workbench (Upgrades
## "corn_shooter", "pumpkin_bomb"). weapon_next (Tab / d-pad down) cycles through the main
## weapons owned, weapon_1..2 (1-2) pick one, both only outside build mode (where those keys
## pick structures) and with no menu open. The off-hand holds the off-hand weapon owned
## (OFFHAND_WEAPONS; there's no pick while there's only one). A main weapon no longer owned (a
## retry from before it was bought) goes back to the pitchfork, an off-hand one out of the hand.
## * Aim with the mouse (the cursor projected onto the combat-height plane through the follow
## camera, corrected for the gun's side offset so shots pass through the cursor; bombs land
## on the ground point under the cursor) or the right stick (camera-relative, radial dead
## zone, last aim kept). The active device switches only on deliberate input: mouse travel
## past a threshold or a click, stick deflection past the dead zone or the trigger.
## * Attack with the main weapon with fire (LMB / RT), and use the off-hand with offhand
## (RMB / LT), each on its own, both at once too. Each needs a fresh press after every reset
## (FarmSim resets on entering and leaving build mode, where the right mouse button is cancel),
## and offhand also after any tick the scarecrow couldn't attack (a menu open, patching; in
## co-op the partner's build mode, which its own machine toggles). Holding either repeats:
## pitchfork a stab every pitchfork_interval: the nearest pitchfork_targets enemies
## within pitchfork_reach and pitchfork_arc of the aim, with a clear line,
## take pitchfork_damage
## corn shooter kernels at fire_rate through FarmProjectiles, shot_damage each (rapid fire
## and heavy seeds)
## pumpkin bomb one every bomb_cooldown, thrown at the aim point (bomb_min_range ..
## bomb_range away; GAMEPAD_THROW ahead with the stick), bursting where it
## lands (PumpkinBombs)
## * Both weapons on the scarecrow's model (WeaponModels), an aim marker, and while a pumpkin
## bomb is ready a ring on the ground where one would land, as wide as its blast.
## While attacking, the model faces the aim.
## Co-op: the partner's weapons on the host read its RemoteControls (aim, fire and offhand, and
## its pick of main weapon come from the partner's game); on the partner's machine its own only
## aims and shows the attack motions (replica: the host attacks), and only the local player's aim
## marker shows.
enum Device { MOUSE, GAMEPAD }
enum Weapon { PITCHFORK, CORN_SHOOTER, PUMPKIN_BOMB }
## A corn shot left the gun (for its sound).
signal fired
## A pitchfork stab (how many it hit), and each enemy it struck (for the sounds).
signal stabbed(hits: int)
signal struck(at: Vector3, enemy_type: int)
## A pumpkin bomb thrown (where it will land).
signal threw(at: Vector3)
## Any attack, with either hand (co-op: the partner's machine shows its motion), and a change of
## main weapon.
signal attacked(weapon: Weapon)
signal switched(weapon: Weapon)
## Lateral offset of the gun from the scarecrow's center line (the prototype's value).
const SIDE_OFFSET := 0.35
## Upgrade ids that unlock the weapons (the pitchfork needs none), and what they're called.
const WEAPON_IDS: Array[String] = ["pitchfork", "corn_shooter", "pumpkin_bomb"]
const WEAPON_NAMES: Array[String] = ["Pitchfork", "Corn shooter", "Pumpkin bombs"]
## The main weapons (Weapon), in the order weapon_next cycles and weapon_1.. pick them, and the
## off-hand ones.
const MAIN_WEAPONS: Array[int] = [Weapon.PITCHFORK, Weapon.CORN_SHOOTER]
const OFFHAND_WEAPONS: Array[int] = [Weapon.PUMPKIN_BOMB]
const SWITCH_ACTIONS: Array[StringName] = [&"weapon_next", &"weapon_1", &"weapon_2"]
## How far ahead a bomb lands when aiming with the stick, and how high it leaves the hand.
const GAMEPAD_THROW := 7.0
const THROW_HEIGHT := 1.6
## Opacity of the bomb's landing ring, and while offhand is held.
const BLAST_ALPHA := 0.45
const BLAST_HELD_ALPHA := 0.9
const WORLD_LAYER := 1
var device: Device = Device.MOUSE
## The main weapon, and the off-hand one (-1: none owned).
var weapon: Weapon = Weapon.PITCHFORK
var offhand: int = -1
## Last valid horizontal aim direction (unit, XZ).
var aim := Vector2(0.0, -1.0)
## World point the mouse aims at (combat-height plane), and the ground point under the cursor;
## valid in MOUSE mode.
var aim_point := Vector3.ZERO
var ground_point := Vector3.ZERO
var shots_fired: int = 0
var stabs: int = 0
var bombs_thrown: int = 0
## Seconds until the next pumpkin bomb is in hand (0 = ready).
var bomb_left: float = 0.0
var remote: RemoteControls
var replica := false
var show_marker := true
## Set by FarmSim: the enemies the pitchfork stabs, and the pumpkin bombs in flight.
var enemies: EnemySystem
var bombs: PumpkinBombs
var models: WeaponModels
var _cfg: GameConfig
## Set by FarmSim: the upgrades (the weapons, fire rate, shot damage).
var campaign: CampaignController
var _player: PlayerCharacter
var _camera: Camera3D
var _shots: FarmProjectiles
var _marker: MeshInstance3D
var _blast: MeshInstance3D
## Ticks until each weapon can attack again (the pumpkin bomb's recharge is bomb_left), kept
## through switches so swapping weapons can't skip a wait.
var _cooldown := PackedInt32Array([0, 0, 0])
var _needs_release := true
var _offhand_needs_release := true
## Ticks so far (tick), and the last one the scarecrow could attack in (step).
var _ticks: int = 0
var _stepped: int = 0
var _mouse_travel: float = 0.0
var _edges := ActionEdges.new()
var _ray := PhysicsRayQueryParameters3D.new()
func setup(cfg: GameConfig, player: PlayerCharacter, camera: Camera3D, shots: FarmProjectiles) -> void:
_cfg = cfg
_player = player
_camera = camera
_shots = shots
_ray.collision_mask = WORLD_LAYER
_ray.collide_with_areas = false
_ray.exclude = [player.get_rid()]
models = WeaponModels.new()
models.setup(player.model, Vector3(SIDE_OFFSET, cfg.combat_height, -cfg.muzzle_distance))
_build_marker()
## Requires fresh fire and offhand presses, so a held button can't attack into a new morning or a
## retry.
func reset() -> void:
_cooldown.fill(0)
_needs_release = true
_offhand_needs_release = true
## A new morning (also after a retry): a pumpkin bomb back in hand.
func ready_for_morning() -> void:
reset()
bomb_left = 0.0
## Whether the weapon goes in the off-hand rather than the hand.
static func is_offhand(w: int) -> bool:
return OFFHAND_WEAPONS.has(w)
## Whether this scarecrow has the weapon: the pitchfork always, the others once bought.
func owns(w: int) -> bool:
if w == Weapon.PITCHFORK:
return true
return w > 0 and w < WEAPON_IDS.size() and campaign != null and Upgrades.owned(campaign.state, WEAPON_IDS[w])
## Takes the weapon up if it's owned: a main weapon into the hand, an off-hand one into the
## off-hand. Returns whether it's there now.
func equip(w: int) -> bool:
if not owns(w):
return false
if is_offhand(w):
_set_offhand(w)
elif w != weapon:
show_weapon(w)
switched.emit(weapon)
return true
## The next main weapon owned after the one in hand.
func cycle() -> void:
var at := MAIN_WEAPONS.find(weapon)
for k in range(1, MAIN_WEAPONS.size()):
if equip(MAIN_WEAPONS[(at + k) % MAIN_WEAPONS.size()]):
return
## Shows the main weapon in hand without the ownership check (co-op: the other scarecrow's, as
## its machine says). An off-hand weapon doesn't go into the hand.
func show_weapon(w: int) -> void:
if not MAIN_WEAPONS.has(w):
return
var next := w as Weapon
if next == weapon and models.weapon == next:
return # (a snapshot saying so again mustn't cut an attack's motion short)
weapon = next
models.show_weapon(weapon)
func _input(event: InputEvent) -> void:
if remote != null:
return
_edges.note(event, SWITCH_ACTIONS)
if event is InputEventMouseMotion:
if device == Device.GAMEPAD:
_mouse_travel += (event as InputEventMouseMotion).relative.length()
if _mouse_travel >= _cfg.mouse_switch_threshold:
device = Device.MOUSE
elif event is InputEventMouseButton and (event as InputEventMouseButton).pressed:
device = Device.MOUSE
elif event is InputEventJoypadButton and (event as InputEventJoypadButton).pressed and event.is_action("fire"):
_to_gamepad()
elif event is InputEventJoypadMotion:
var jm := event as InputEventJoypadMotion
if (jm.axis == JOY_AXIS_TRIGGER_RIGHT or jm.axis == JOY_AXIS_TRIGGER_LEFT) and jm.axis_value > 0.5:
_to_gamepad()
## Every tick, attacking or not (building, patching): the bomb's recharge, the off-hand weapon,
## and the pick of main weapon (the switch actions count only when can_switch: outside build
## mode, no menu open; the partner's pick comes from its game).
func tick(dt: float, can_switch: bool) -> void:
_ticks += 1
bomb_left = maxf(bomb_left - dt, 0.0)
models.set_bomb_charge(1.0 - bomb_left / _cfg.bomb_cooldown if _cfg.bomb_cooldown > 0.0 else 1.0)
if not owns(weapon):
equip(Weapon.PITCHFORK)
if not owns(offhand):
_set_offhand(-1)
for w in OFFHAND_WEAPONS:
if equip(w):
break
if remote != null:
if remote.weapon >= 0:
equip(remote.weapon)
return
var p := {}
for a in SWITCH_ACTIONS:
p[a] = _edges.pressed(a)
if not can_switch:
return
if p[&"weapon_next"]:
cycle()
for k in MAIN_WEAPONS.size():
if p[SWITCH_ACTIONS[k + 1]]:
equip(MAIN_WEAPONS[k])
## One physics tick while the scarecrow can attack: update the aim, then attack with the main
## weapon if fire is held, and use the off-hand one if offhand is held, each if it's ready.
func step(_dt: float) -> void:
_update_aim()
var held := _held(&"fire")
var off_held := _held(&"offhand")
for i in _cooldown.size():
_cooldown[i] = maxi(_cooldown[i] - 1, 0)
if _ticks - _stepped > 1:
_offhand_needs_release = true # couldn't attack last tick (a menu, the partner's build mode)
_stepped = _ticks
if replica:
if held:
_player.face_aim(aim, 0.35)
_show_attack()
return
if _needs_release and not held:
_needs_release = false
if _offhand_needs_release and not off_held:
_offhand_needs_release = false
if off_held and not _offhand_needs_release:
_player.face_aim(aim, 0.35)
use_offhand()
if held and not _needs_release:
_player.face_aim(aim, 0.35)
attack()
## The main weapon attacks along the aim, if it's ready. Returns whether it did.
func attack() -> bool:
return _use(weapon)
## The off-hand weapon is used (a pumpkin bomb thrown at the aim point), if one is ready.
## Returns whether it was.
func use_offhand() -> bool:
return offhand >= 0 and _use(offhand)
## A scripted attack (the soak's scarecrow, tests): aims at target and attacks with the main
## weapon if it's ready.
func attack_toward(target: Vector2) -> bool:
_aim_at(target, weapon == Weapon.CORN_SHOOTER)
return attack()
## The same with the off-hand weapon (a pumpkin bomb thrown at target).
func offhand_toward(target: Vector2) -> bool:
_aim_at(target, false)
return use_offhand()
## Attacks so far, with any weapon.
func attacks() -> int:
return stabs + shots_fired + bombs_thrown
## Ticks between shots, and a shot's damage, with upgrades.
func interval_ticks() -> int:
var state := campaign.state if campaign != null else null
return maxi(1, roundi(Engine.physics_ticks_per_second / Upgrades.value(_cfg, state, "fire_rate")))
func shot_damage() -> int:
return roundi(Upgrades.value(_cfg, campaign.state if campaign != null else null, "shot_damage"))
## Ticks between pitchfork stabs.
func stab_ticks() -> int:
return maxi(1, roundi(_cfg.pitchfork_interval * Engine.physics_ticks_per_second))
## Where a bomb thrown now lands: the ground point aimed at (GAMEPAD_THROW ahead with the stick),
## bomb_min_range .. bomb_range from the scarecrow.
func throw_target() -> Vector3:
var p := Vector2(_player.global_position.x, _player.global_position.z)
var want := Vector2(ground_point.x, ground_point.z) - p if device == Device.MOUSE else aim * GAMEPAD_THROW
var dir := want.normalized() if want.length() > 1e-3 else aim
var at := p + dir * clampf(want.length(), _cfg.bomb_min_range, _cfg.bomb_range)
return Vector3(at.x, 0.0, at.y)
func _held(action: StringName) -> bool:
return remote.held(action) if remote != null else Input.is_action_pressed(action)
func _use(w: int) -> bool:
if _cooldown[w] > 0:
return false
match w:
Weapon.CORN_SHOOTER:
_cooldown[w] = interval_ticks()
_shoot()
Weapon.PUMPKIN_BOMB:
if bomb_left > 0.0 or not _throw():
return false
_:
_cooldown[w] = stab_ticks()
_stab()
attacked.emit(w)
return true
func _set_offhand(w: int) -> void:
if w != offhand:
offhand = w
models.show_offhand(w)
func _aim_at(target: Vector2, from_muzzle: bool) -> void:
var p := Vector2(_player.global_position.x, _player.global_position.z)
var to := target - p
if to.length() > 1e-3:
aim = PlayerInput.muzzle_corrected_aim(to, to.normalized()) if from_muzzle else to.normalized()
aim_point = Vector3(target.x, _cfg.combat_height, target.y)
ground_point = Vector3(target.x, 0.0, target.y)
device = Device.MOUSE
_player.face_aim(aim, 0.35)
func _shoot() -> void:
var origin := Vector3(_player.global_position.x, _cfg.combat_height, _player.global_position.z)
var dir := Vector3(aim.x, 0.0, aim.y)
var right := Vector3(-aim.y, 0.0, aim.x)
var muzzle := origin + dir * _cfg.muzzle_distance + right * SIDE_OFFSET
shots_fired += 1
_shots.fire(origin, muzzle, dir, shot_damage())
models.attack(Weapon.CORN_SHOOTER)
fired.emit()
## The nearest few enemies in reach, in the arc, and in the clear take a stab.
func _stab() -> int:
stabs += 1
models.attack(Weapon.PITCHFORK)
var hits := 0
if enemies != null:
var es := enemies
var p := Vector2(_player.global_position.x, _player.global_position.z)
var cos_half := cos(deg_to_rad(_cfg.pitchfork_arc) * 0.5)
var found: Array = [] # [distance, slot]
for d in es.active_count:
if es.alive[d] == 0:
continue
var e := Vector2(es.pos_x[d], es.pos_z[d])
var dist := e.distance_to(p)
if dist > _cfg.pitchfork_reach + es.t_hit_radius[es.type[d]]:
continue
if dist > 0.3 and (e - p).dot(aim) < cos_half * dist:
continue
if _clear_line(p, e):
found.append([dist, d])
found.sort_custom(func(a: Array, b: Array) -> bool: return a[0] < b[0])
for k in mini(found.size(), _cfg.pitchfork_targets):
var d: int = found[k][1]
var at := Vector3(es.pos_x[d], _cfg.combat_height, es.pos_z[d])
var type := es.type[d]
if es.apply_hit(d, _cfg.pitchfork_damage):
hits += 1
struck.emit(at, type)
stabbed.emit(hits)
return hits
func _throw() -> bool:
if bombs == null:
return false
var p := _player.global_position
var hand := Vector3(p.x + aim.y * 0.4, THROW_HEIGHT, p.z - aim.x * 0.4) # the left
var to := throw_target()
if not bombs.throw(hand, to, _cfg.bomb_damage, _cfg.bomb_radius):
return false
bomb_left = _cfg.bomb_cooldown
models.set_bomb_charge(0.0)
bombs_thrown += 1
threw.emit(to)
return true
## The partner's machine: the main weapon's attack motion on its own cadence (the host attacks;
## its throws show the bomb, and empty the off-hand).
func _show_attack() -> void:
if _cooldown[weapon] > 0:
return
_cooldown[weapon] = interval_ticks() if weapon == Weapon.CORN_SHOOTER else stab_ticks()
models.attack(weapon)
func _clear_line(a: Vector2, b: Vector2) -> bool:
if not is_inside_tree():
return true
_ray.from = Vector3(a.x, _cfg.combat_height, a.y)
_ray.to = Vector3(b.x, _cfg.combat_height, b.y)
return get_world_3d().direct_space_state.intersect_ray(_ray).is_empty()
func _update_aim() -> void:
if remote != null:
aim = remote.aim
aim_point = remote.aim_point
ground_point = remote.ground_point
device = remote.device as Device
return
var b := _camera.global_transform.basis
var fwd := Vector3(-b.z.x, 0.0, -b.z.z).normalized()
var right := Vector3(b.x.x, 0.0, b.x.z).normalized()
var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", _cfg.aim_dead_zone)
if stick != Vector2.ZERO:
_to_gamepad()
var w := right * stick.x + fwd * stick.y
aim = Vector2(w.x, w.z).normalized()
elif device == Device.MOUSE:
aim_point = _cursor_on_plane(_cfg.combat_height)
ground_point = _cursor_on_plane(0.0)
var p := _player.global_position
aim = PlayerInput.muzzle_corrected_aim(Vector2(aim_point.x - p.x, aim_point.z - p.z), aim)
func _cursor_on_plane(height: float) -> Vector3:
var screen := _camera.get_viewport().get_mouse_position()
var o := _camera.project_ray_origin(screen)
var d := _camera.project_ray_normal(screen)
if absf(d.y) < 1e-5:
return Vector3(o.x, height, o.z)
return o + d * ((height - o.y) / d.y)
func _to_gamepad() -> void:
device = Device.GAMEPAD
_mouse_travel = 0.0
func _process(_delta: float) -> void:
if _player == null:
return
_marker.visible = show_marker
if device == Device.MOUSE:
_marker.global_position = Vector3(aim_point.x, _cfg.combat_height, aim_point.z)
else:
var p := _player.get_global_transform_interpolated().origin
_marker.global_position = Vector3(p.x + aim.x * 3.0, _cfg.combat_height, p.z + aim.y * 3.0)
# A pumpkin bomb ready in the off-hand: where it would land, brighter while offhand is held.
var bomb := offhand == Weapon.PUMPKIN_BOMB and bomb_left == 0.0
_blast.visible = show_marker and bomb
if _blast.visible:
var at := throw_target()
_blast.global_position = Vector3(at.x, 0.1, at.z)
var held := remote == null and Input.is_action_pressed("offhand")
(_blast.material_override as StandardMaterial3D).albedo_color.a = BLAST_HELD_ALPHA if held else BLAST_ALPHA
func _build_marker() -> void:
_marker = _ring(0.2, 0.3, Color(1.0, 0.85, 0.25))
_marker.name = "AimMarker"
_blast = _ring(_cfg.bomb_radius - 0.08, _cfg.bomb_radius, Color(1.0, 0.55, 0.12, BLAST_ALPHA))
_blast.name = "BlastMarker"
func _ring(inner: float, outer: float, color: Color) -> MeshInstance3D:
var torus := TorusMesh.new()
torus.inner_radius = inner
torus.outer_radius = outer
torus.rings = 48
torus.ring_segments = 6
var mat := StandardMaterial3D.new()
mat.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
mat.albedo_color = color
mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA if color.a < 1.0 else BaseMaterial3D.TRANSPARENCY_DISABLED
mat.no_depth_test = true
mat.render_priority = 1
var mi := MeshInstance3D.new()
mi.mesh = torus
mi.material_override = mat
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
mi.top_level = true
mi.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(mi)
return mi