Debian Codegraph @

scripts/fighter_ai.lua

raw symbols SCIP
1 local v2 = require 'dokidoki.v2'
2
3 -- shot range
4 local shot_range = 200
5 -- try to stay this far away when you're out of ammo
6 local run_distance = 200
7
8 -- true when we've shot everything and want to make a distance, false means
9 -- we're approaching to attack
10 local running = false
11
12 local target = false
13 local on_screen = true
14
15 local function retarget ()
16 target = game.targeting.get_nearest_of_type(self, 'bomber') or
17 game.targeting.get_nearest_of_type(self, 'fighter') or
18 game.targeting.get_nearest_of_type(self, 'frigate') or
19 game.targeting.get_nearest_of_type(self, 'factory')
20 end
21
22 -- basically, the behaviour is to go towards the target and attack it, then
23 -- when you're out of ammo run away until you've got your ammo back and have
24 -- gone a certain distance
25
26 function update()
27 -- if we go from on to off screen, retarget
28 local new_on_screen = game.targeting.on_screen(self.transform.pos)
29 if (on_screen and not new_on_screen)
30 or not target
31 or target.dead
32 or math.random() < 0.005 then
33 retarget()
34 end
35 on_screen = new_on_screen
36
37 if target then
38 game.tracing.trace_line(self.transform.pos, target.transform.pos)
39 end
40
41 if target then
42 local to_target = target.transform.pos - self.transform.pos
43 local dist_squared = v2.sqrmag(to_target)
44
45 if running then
46 -- run away until you have full ammo and are far enough away
47
48 local too_close = dist_squared < run_distance^2
49 -- if you're too close to the target then turn away
50 if too_close then
51 self.ship.go_away(target.transform.pos, true)
52 else
53 self.ship.thrust()
54 end
55
56 if not self.fighter_shooting.is_empty() and not too_close then
57 running = false
58 end
59 else
60 -- go towards the target and attack!
61
62 self.ship.go_towards(target.transform.pos, true)
63
64 -- maybe shoot
65 if self.fighter_shooting.is_ready_to_shoot() then
66 local facing = self.transform.facing
67 if dist_squared <= shot_range * shot_range
68 and v2.dot(to_target, facing) > 0
69 and v2.dot(to_target, facing)^2 > 0.97 * dist_squared then
70 self.fighter_shooting.shoot()
71 end
72 end
73
74 -- if out of shots then run away
75 if self.fighter_shooting.is_empty() then
76 running = true
77 end
78 end
79 end
80 end