0 votes

I got this flying enemy with some problems: sometimes he stops chasing the Player even if he is in the enemy's range and ,most important, I can't change his speed! Script:

extends KinematicBody2D

var speed = 200
var move = Vector2.ZERO
var player = null
var follow = false
var is_dead = false
export (int) var life = 1
var awake = false

func _physics_process(delta):
    move = Vector2.ZERO 
    if player != null:
        move = position.direction_to(player.position) * speed 
    else:
        move = Vector2.ZERO
        if awake == false && is_dead == false:
            $AnimatedSprite.play("default")

    move = move.normalized()
    move = move_and_collide(move)
    if follow == true && is_dead == false:
        $AnimatedSprite.play("follow")


func _on_Area2D_body_entered(body):
    if body.name == "Player":
        if follow == false:
            awake = true
            $AnimatedSprite.play("awake")
            yield(get_tree().create_timer(0.8), "timeout")
            follow = true
            awake = false
        player = body


func _on_Area2D_body_exited(body):
    player = null
    follow = false




func dead():
    life -= 1
    if life < 0:
        is_dead = true
        Globals.nemici -= 1
        speed = Vector2(0, 0)
        $AnimatedSprite.play("dead")
        $CollisionShape2D.call_deferred("set_disabled", true)
        $Area2D2/CollisionShape2D.call_deferred("set_disabled", true)
        $Timer.start()
    $Particles2D.emitting = true
    yield(get_tree().create_timer(0.2), "timeout")
    $Particles2D.emitting = false
func _on_Timer_timeout():
        call_deferred("free")





func _on_Area2D2_body_entered(body):
    if body.name == "Player":
        body.dead()
        Globals.gameover = 4

When I change the variable "speed" his speed doesn't change.

asked Jun 20 in Engine by MightyRat (55 points)

1 Answer

0 votes
Best answer

you normalize the move vector after having speed added to it, that makes the speed uselss, add speed only at the moveandslide function to move (and I'd also advice you to multiple it with delta too, that changes the speed based on the framerate so movement isn't increased or decreased just because the framrate changes).

something like this is what you'd want

move_and_slide(move*speed*delta)

or you could do it where the move variable is changed...

move = move.normalized()*speed*delta
answered Jun 20 by zen3001 (156 points)
edited Jun 22 by zen3001
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 How to use this Q&A? before posting your first questions.