Walking and shooting enemy

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By randomguy

I want to make an enemy stop walking and shoot a bullet every 5 seconds. Here is my current enemy code:

extends KinematicBody2D

const BULLET = preload(“res://bullet.tscn”)
const GRAVITY = 10
const SPEED = 50
const UP = Vector2.UP

var velocity = Vector2()
var direction = 1

func _physics_process(delta):
velocity.x = SPEED * direction

if direction == 1:
	$AnimatedSprite.flip_h = false
	$AnimatedSprite.flip_h = true


velocity.y += GRAVITY
velocity = move_and_slide(velocity, UP)

if is_on_wall():
	direction = direction * -1
	$RayCast2D.position.x *= -1
if $RayCast2D.is_colliding() == false:
	direction *= -1
	$RayCast2D.position.x *= -1

func _on_Timer_timeout():
var bullet = BULLET.instance()
bullet.position = $Position2D.global_position

:bust_in_silhouette: Reply From: VitusVeit

I tink an easy way of doing this is creating a boolean can_walk and adding an if before moving the player:

if can_walk: 
        velocity.x = SPEED * direction

Then, when the timer finishes, setting can_walk to false, shooting, and waiting for some seconds and setting can_walk to true, like this:

func onTimertimeout():
     can_walk = false
     var bullet = BULLET.instance()
     bullet.position = $Position2D.globalposition
     yield(get_tree().create_timer(0.5), "timeout") #Wait 0,5 seconds
     can_walk = true

Hope it helps!

It works, thanks for your help!

randomguy | 2022-04-24 12:29