+#define UNIT_SCAN_RANGE_Y MAP_H/4
+#define UNIT_SCAN_RANGE_X MAP_W/4
; handles cpu inputs
+ ; chaser CPU script
; inputs:
; de: actor
; returns:
; bc: next state
unit_handle_cpu_inputs:
+#define MOVE_MADE scratch
+ ; clear move made buffer
+ xor a, a
+ ld [MOVE_MADE], a
+
+ ; there's a change the
+ ; unit will just move randomly anyway
+ call rand
+ and a, 0x7F
+ cp a, 0
+ jp z, @random_move
+
+ ; otherwise follow player
+
+ ; check y position
+ ; and follow player in y direction if player is in range
+ ld hl, player_unit+act_pos_y
+ ld a, [hl]
+ ld b, a ; b = player y pos
+ push de
+ ld hl, act_pos_y
+ add hl, de
+ ld a, [hl] ; a = act y pos
+ call distance
+ pop de
+
+ ; are we in scan range?
+ cp a, UNIT_SCAN_RANGE_Y
+ jr nc, @not_in_y_range REL
+ cp a, 1
+ jr z, @not_in_y_range REL
+
+ ; which direction?
+ ld a, c
+ cp a, DISTANCE_BGTA
+ push af
+ call nz, unit_try_move_up
+ pop af
+ call z, unit_try_move_down
+ ld a, 1
+ ld [MOVE_MADE], a
+@not_in_y_range:
+
+ ; check x position
+ ; and follow player in x direction if player is in range
+ ld hl, player_unit+act_pos_x
+ ld a, [hl]
+ ld b, a ; b = player x pos
+ push de
+ ld hl, act_pos_x
+ add hl, de
+ ld a, [hl] ; a = act x pos
call distance
+ pop de
+
+ ; are we in scan range?
+ cp a, UNIT_SCAN_RANGE_X
+ jr nc, @not_in_x_range REL
+ cp a, 1
+ jr z, @not_in_x_range REL
+
+ ; which direction?
+ ld a, c
+ cp a, DISTANCE_BGTA
+ push af
+ call nz, unit_try_move_left
+ pop af
+ call z, unit_try_move_right
+ ld a, 1
+ ld [MOVE_MADE], a
+@not_in_x_range:
+@random_move:
+
+ ; call random move if move was not made
+ ld a, [MOVE_MADE]
+ cp a, 0
+ call z, unit_cpu_random_move
- call unit_cpu_random_move
+@move_made:
ld bc, st_unit_delay_to_active
ret
+#undefine MOVE_MADE
; moves actor into a random direction