Hello, I am making an enemy slime in Godot and have got most things working. I tried adding a feature that would make the slime move towards the player once it had found it. But, this intersects with the natural patrolling of the enemy, as it normally just goes forward and goes back when it reaches an edge. But now, I am having trouble making these two features work. Here is the code of my slime:
extends KinematicBody2D
onready var animatedSprite = $AnimatedSprite
onready var downCast = $DownRay
onready var rightCast = $RightRay
onready var hitbox = get_node("Hitbox/CollisionShape2D")
onready var playerChase = get_node("PlayerChase/CollisionShape2D")
onready var player = get_node("Level/Characters/PlayerRoot/Player")
var gravity = 60
var motion = Vector2(0, 0)
var turnDelay = 1
var speed = 32
var movingLeft = true
var attacking = false
var playerInRange = false
var playerFound = false
func _process(delta):
detection()
attack()
moveCharacter()
animate()
if playerFound:
playerChase.disabled = false
else:
playerChase.disabled = true
func animate():
if attacking:
return
if speed != 0:
animatedSprite.play("Run")
else:
animatedSprite.play("Idle")
func moveCharacter():
if !player:
motion.x = -speed if movingLeft else speed
motion.y += gravity
else:
motion = (player.position - position).normalized()
if not is_on_floor():
motion.y += gravity
motion = move_and_slide(motion, Vector2.UP)
func detection():
if rightCast.is_colliding():
var collider = rightCast.get_collider()
if collider && collider.name == "Player":
motion = Vector2.ZERO
playerInRange = true
playerFound = true
elif !rightCast.is_colliding():
playerInRange = false
if !downCast.is_colliding() && is_on_floor():
if rightCast.is_colliding():
motion = Vector2.ZERO
else:
if player:
return
print("turned")
movingLeft = !movingLeft
scale.x = -scale.x
func attack():
if playerInRange && animatedSprite.animation != "Attack":
animatedSprite.play("Attack")
attacking = true
elif playerInRange && !animatedSprite.playing:
attacking = false
func _on_AnimatedSprite_frame_changed():
if animatedSprite.frame >= 2 && animatedSprite.frame <= 4 && animatedSprite.animation == "Attack":
hitbox.disabled = false
print("attack collided")
else:
hitbox.disabled = true
print("player was not in range")
func _on_AnimatedSprite_animation_finished():
if animatedSprite.animation == "Attack":
attacking = false
If anyone can help me on how to add these two features I would very much appreciate it. Thank you for reading