64 lines
2.4 KiB
GDScript
64 lines
2.4 KiB
GDScript
extends "res://objects/enemy/enemy.gd"
|
|
|
|
## the floor directions a fiend can be attached to
|
|
const DIRS = [Vector2.DOWN, Vector2.RIGHT, Vector2.UP, Vector2.LEFT]
|
|
|
|
export var move_speed: float = 50.0
|
|
export var clockwise: bool = false
|
|
|
|
## keep options for shape query around because they will mostly stay the same
|
|
onready var floor_test = Physics2DShapeQueryParameters.new()
|
|
onready var test_shape = $FloorTestShape
|
|
|
|
## index of the current floor direction
|
|
var floor_direction: int = 0
|
|
## builds up movement so that fractional movement carries on
|
|
var movement_accumulator: float = 0.0
|
|
|
|
func _ready():
|
|
# scale animation to move speed
|
|
$AnimatedSprite.speed_scale = inverse_lerp(0.0, 50.0, move_speed)
|
|
# flip if going backwards
|
|
if clockwise:
|
|
$AnimatedSprite.flip_h = true
|
|
# fill in shape query parameters that stay the same
|
|
floor_test.set_shape(test_shape.shape)
|
|
floor_test.collision_layer = 1
|
|
# loop through possible directions to find which one should start on
|
|
for i in DIRS.size():
|
|
if is_on_surface(DIRS[i]):
|
|
floor_direction = i
|
|
break
|
|
# adjust to difficulty
|
|
move_speed *= Game.enemy_speed_factor
|
|
|
|
func _physics_process(delta):
|
|
# add to accumulator
|
|
movement_accumulator += move_speed * delta
|
|
# move one pixel at a time until out of integer movment
|
|
while movement_accumulator >= 1.0:
|
|
# check next direction for wall if clockwise, else previous
|
|
var offset = 1 if clockwise else -1
|
|
# movement dir should be the next direction from the floor direction
|
|
var move_dir = posmod(floor_direction + offset, DIRS.size())
|
|
# check if gone off edge
|
|
if !is_on_surface(DIRS[floor_direction]):
|
|
# change to next floor direction
|
|
floor_direction = posmod(floor_direction - offset, DIRS.size())
|
|
# check if collided with wall
|
|
elif is_on_surface(DIRS[move_dir]):
|
|
# new floor direction is where wall is
|
|
floor_direction = move_dir
|
|
# move along new floor direction
|
|
position += DIRS[posmod(floor_direction + offset, DIRS.size())]
|
|
# 1 pixel of movement spent from accumulator
|
|
movement_accumulator -= 1.0
|
|
|
|
## tests if there is a floor 1 pixel in the direction tested
|
|
func is_on_surface(dir):
|
|
# get the physics space state
|
|
var space_state = get_world_2d().direct_space_state
|
|
# set position to test box at, moved 1 pixel in the direction tested
|
|
floor_test.transform = test_shape.global_transform.translated(dir)
|
|
# collide_shape returns array of collisions, if not empy there is a floor there
|
|
return not space_state.collide_shape(floor_test, 1).empty()
|