How to stop kinematicbody2d moving after it finished jumping??

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

Hello godot community.
I am currently working on creating an enemy that jumps towards the player’s position using KinematicBody2D. Although I was able to make the enemy jump towards the player’s position, it continues to move even after landing for some reason. Could you please teach me the solution to this problem?

extends KinematicBody2D

var jump_height = 500
var horizontal_speed = 500
var gravity = 1000
var direction = 1
var velocity = Vector2.ZERO

func _ready():
	var player_pos = get_node("../Player").get_global_position()
	var self_pos = get_global_position()

func _physics_process(delta):
	if velocity.x>0:
	elif velocity.x<0:
	if is_on_wall() or not $Position2D/FloorRay.is_colliding() and is_on_floor():
		direction = direction * -1

var player_pos = get_node("../Player").get_global_position() 
	var self_pos = get_global_position()        
	var jump_distance = player_pos - self_pos

	if Input.is_action_just_pressed("jump"):
		# Calculate the velocity required to reach the player's position
		velocity = jump_distance.normalized()
		velocity.x *= horizontal_speed 
		velocity.y = -jump_height
        # Apply gravit
		velocity.y += gravity * delta
	move_and_slide(velocity, Vector2.UP)
:bust_in_silhouette: Reply From: trainrudder


I am also beginner but I believe you can use signal body_entered to stop motion when it collides with platform or any other body.

:bust_in_silhouette: Reply From: zhyrin

When you start the jump, you calculate the horizontal velocity, but you never set it back to 0.
I assume you would want it to stop once it hits the ground or a wall, correct?

Yes, that is correct. How can I set the value to zero, if I may ask?

amaou310 | 2023-02-12 12:05

When you check if it’s on the wall or floor you set it like so velocity.x = 0

zhyrin | 2023-02-15 20:33