I want my enemy to slow down to a stop

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

First year of programming, and so far I’m just practicing and trying to make the mechanics I wanna make,

My character has a flashlight that uses an Area2D and when the enemy enters the Area2D it’s supposed to gradually slow it’s speed before coming to a complete stop and then dying.

I tried to using interpolation, but when I did it with the enemy’s speed, it would just immediately lower the speed, but never come to a stop.

Script for enemy “Imp” (KinematicBody2D):

extends KinematicBody2D

export var speed = 25
export var default_speed = 25

var velocity = Vector2.ZERO

var player

var rng = RandomNumberGenerator.new()

func _ready():
	player = get_tree().root.get_node("Root/Player") 

func _physics_process(delta):
	velocity = Vector2.ZERO
	if player:
		velocity = position.direction_to(player.position) * speed
	velocity = move_and_slide(velocity)

Script for flashlight “Light” (Area2D):

extends Area2D

var friction = 0.60

func _ready():

func _on_Light_body_entered(body):
	if "Imp" in body.name:
		body.speed = lerp (body.speed, 0, friction)

func _on_Light_body_exited(body):
	if "Imp" in body.name:
		body.speed = body.default_speed

Please format your code for the forum (it’s really hard to read otherwise). To do that…

  • Edit your post
  • Select the block of code
  • Press the small { } button in the forum editor’s toolbar
  • Check the Preview panel to ensure proper formatting.

jgodfrey | 2022-08-15 20:13

Sorry about that. I couldn’t figure out how to. I fixed it so it’s more readable now.

NLgodot | 2022-08-15 22:00

Hey NLGodot, when you write {body.speed = lerp(…} that will just immediately change the body.speed value to a new value. Based on the values you’ve listed above you have basically written this:

body.speed = lerp(25, 0, 0.6)

lerp(25, 0, 0.6) will just give a value of 10 which is why your enemy slows down a bit and then stays at that one speed. I think you’d be better off using a tween for what you’re trying to do. A tween will gradually change the value of one property to another value which sounds like just what you need. You could make a function in your Enemy script (maybe called SlowDown) which contains the Tween code. Then instead of writing body.speed = … you would just write body.SlowDown().

dacess123 | 2022-08-16 09:00

Thank you! I’m going to look into this and try it.

NLgodot | 2022-08-16 19:16

It worked!! Thank you so much!! And I learned more about Tweens too!

NLgodot | 2022-08-16 20:33

Glad it worked :slight_smile:

dacess123 | 2022-08-16 20:36