+1 vote

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 physicsprocess(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 onTimertimeout():
var bullet = BULLET.instance()
bullet.position = $Position2D.global

Godot version 3.4.4
in Engine by (28 points)

1 Answer

0 votes

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 canwalk to false, shooting, and waiting for some seconds and setting canwalk 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!

by (99 points)

It works, thanks for your help!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.