Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends KinematicBody2D
- onready var detectionZone = $DetectionZone
- onready var sprite = $AnimatedSprite
- onready var hitBox = $HitBoxPivot/HitBox/CollisionShape2D
- onready var bodies = []
- var vector_to_enemy = Vector2.ZERO
- var velocity = Vector2.ZERO
- var state = IDLE
- var attack_range = 50
- var is_attacking = false
- const MAX_SPEED = 20
- enum {IDLE, RUN, ATTACK, DEATH}
- func _ready():
- state = IDLE
- func _physics_process(_delta):
- match state:
- IDLE:
- bodies = detectionZone.get_overlapping_bodies()
- bodies.erase(self)
- sprite.play("Idle")
- if bodies.size() > 0:
- state = RUN
- RUN:
- var closest_enemy = find_closest_enemy(bodies)
- if closest_enemy == null:
- state = IDLE
- if self.position.x <= closest_enemy.position.x:
- velocity = self.position.direction_to(closest_enemy.position - Vector2(30,0))
- sprite.flip_h = false
- elif self.position.x > closest_enemy.position.x:
- velocity = self.position.direction_to(closest_enemy.position + Vector2(30,0))
- sprite.flip_h = true
- velocity = velocity.normalized()
- velocity = move_and_slide(velocity * MAX_SPEED)
- sprite.play("Run")
- var d_self_y = self.position.y
- var d_enemy_y = closest_enemy.position.y
- if abs(d_enemy_y - d_self_y) < rand_range(5, 15):
- state = ATTACK
- ATTACK:
- if bodies.size() == 0:
- state = IDLE
- sprite.play("Attack1")
- hitBox.disabled = false
- if sprite.flip_h == true:
- get_node("HitBoxPivot").set_scale(Vector2(-1, 1))
- DEATH:
- sprite.play("Death")
- queue_free()
- func find_closest_enemy(_bodies):
- var min_dist = 99999
- var closest_enemy
- for body in _bodies:
- if body != null:
- var dist = self.position.distance_to(body.position)
- if (dist < min_dist):
- min_dist = dist
- closest_enemy = body
- return closest_enemy
- func _on_AnimatedSprite_animation_finished():
- if sprite.animation == "Death":
- queue_free()
- if sprite.animation == "Attack1":
- hitBox.disabled = true
- func _on_HurtBox_area_entered(_area):
- state = DEATH
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement