¿How can i add gravity to an enemy?

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

Hello, i do have an kinematic body called “Enemy” that moves and slides toward the player, but only in z and x, i dont want him to “fly” towards the player, just to have some gravity to he stays on the ground, how can i do this? thanks for any help.

:bust_in_silhouette: Reply From: Ertain

Have you tried adding something like “-9.8” to the “Y” component of the Enemy KinematicBody? Maybe add it in the _physics_process()?

I tryed doing it, but it gets stuck and moves rarely, im using a flat terrain, do you know why this happens? thanks

Arielrandal | 2021-06-26 15:30

Could you post the code used to move the Enemy node? BTW, to post code here, use the button above the text field for code.

Ertain | 2021-06-26 17:27

there is the code, i used daniel buckley tutorial,
func _physics_process(delta): if is_on_floor(): gravity = 0 else: gravity = -0.98 if Input.is_action_pressed("shift"): moveSpeed = 16 if Input.is_action_just_released("shift"): moveSpeed = 10 if translation.distance_to(player.translation) <= attackRange and alerta<10: var dir = (player.translation - translation).normalized() dir.y = gravity move_and_slide(dir * moveSpeed, Vector3.UP) if alerta >= 10: var dir = (player.translation - translation).normalized() dir.y = gravity move_and_slide(dir * moveSpeed, Vector3.UP)
Shift is to increase speed when player is running, and alerta is for when he gets shoot no matter the distance to player, he starts chasing him. I tryed to add the if is_on_floor but as i said it keeps moving rarely and gets stuck.

Arielrandal | 2021-06-26 17:56

From what I can tell, you should continuously apply the gravity, not just when the Enemy is on the floor (is_on_floor() can be spotty and unusable on some surfaces).

Ertain | 2021-06-27 00:47

the problem could be with the collision shape, if it’s not a capsule, make it one

theMX89 | 2021-06-27 07:02

ohhh yeah, that was the problem, much thanks for all the help, it was a sphere collision shape before, thanks

Arielrandal | 2021-06-27 18:49

:bust_in_silhouette: Reply From: theMX89

instead of an kinematicbody, you can use an riggidbody.
a riggidbody already has all physiks