Rotate Enemy(2d) to player

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

Hi I am new to coding and I have an enemy code where it follows a player

extends KinematicBody2D

export var min_speed = 150
export var max_speed = 300
var target = null

var velocity = Vector2()

func _ready():
	pass
	
func _physics_process(delta):
	if target:
		var velocity = global_position.direction_to(target.global_position)
		move_and_collide(velocity * rand_range(min_speed, max_speed) * delta)

func _on_VisibilityNotifier2D_screen_exited():
	queue_free()

func _on_PlayerSensor_body_entered(body):
	target = body

Here is where it is summoned:

    extends Node2D

var Mob = preload("res://Scenes/Enemy.tscn")
onready var mobs = get_node("Mob")

func _ready():
	randomize()
	$Player.position = $StartingPos.position
	$StartTimer.start()
	
func restart():
	$Player.position = $StartingPos.position

func _on_StartTimer_timeout():
	mobs.get_node("MobTimer").start()


    func _on_MobTimer_timeout():
    	mobs.get_node("MobSpawner/MobSpawnerLocation").offset = randi()
    	var mob = Mob.instance()
    	add_child(mob)
    	mob.position = mobs.get_node("MobSpawner/MobSpawnerLocation").position
    	var direction = mobs.get_node("MobSpawner/MobSpawnerLocation").rotation + PI / 2
    	direction += rand_range(-PI / 4, PI / 4)
    	mob.rotation = direction
    	mob.velocity = direction

here is all the thing the enemy it has:
KinematicBody2d
-sprite
-collision
-visibility
-area2d(player sensor)

I wanted to make it only rotate to the player once and does not chase the player like it only goes one straight line. How can i make it not chase?

:bust_in_silhouette: Reply From: klaas

Hi,
have a look at the code

extends KinematicBody2D

export var min_speed = 150
export var max_speed = 300
var target = null

var velocity = Vector2()

here in the _physics_process if a target is set a velocity is calculated in the direction of the target. But you want at only once when a target is set.

func _physics_process(delta):
    if target:
        var velocity = global_position.direction_to(target.global_position)
        move_and_collide(velocity * rand_range(min_speed, max_speed) * delta)

and here the target gets set

func _on_PlayerSensor_body_entered(body):
    target = body

lets modify it

var velocity:Vector2 #make this variable persistent
func _on_PlayerSensor_body_entered(body):
    target = body
    # we only calculate velocity once when the target gets set
    var velocity = global_position.direction_to(target.global_position) 
func _physics_process(delta):
    if target:
        # now the velocity was calculated once we only have to apply it here
        move_and_collide(velocity * rand_range(min_speed, max_speed) * delta)