Make a KinematicBody2D flip to face another one (2D fighting game)

Attention Topic was automatically imported from the old Question2Answer platform.

Good morning/afternoon/evening

I am making a 2D fighting game and I need help making the characters face each other whatever their position on screen. Flipping horizontaly would fit well for this case, but I have no idea how to start the code. Can anyone help me? Thank you!

May I suggest checking the vector between the combatants via the dot product? When the angle between them is greater than zero, the combatants are facing each other. If not, you can flip the combatant’s Sprites (use the flip_h property of a Sprite node) so that they are facing each other.

Ertain | 2020-06-02 05:38

Thank you for your suggestion! I started looking at the dot product and finding a way to apply it in my code.

migraman | 2020-06-02 16:41

When the angle between them is greater than zero, the combatants are facing each other

do you mean the angle or the distance?

anyways, see if this is working for you:

Player’s script:

func _physics_process(delta):
look_at_enemy()

func look_at_enemy():
if enemy_pos.x > self.position.x:
self.get_node("Sprite").flip_h = false
else:
self.get_node("Sprite").flip_h = true

Enemy’s script:

func _physics_process(delta):
look_at_player()

func look_at_player():
if player_pos.x > self.position.x:
self.get_node("Sprite2").flip_h = false
else:
self.get_node("Sprite2").flip_h = true

the NodeTree:

Node2D
Player (KinematicBody2D)
CollisionShape2D
Sprite
Player (KinematicBody2D)
CollisionShape2D2
Sprite2

hope it helps

Thank you so much! This is definitely the code I needed! =)
For some reason it worked with one of my characters but not the other. It’s my mistake for sure, but I will figure it out

migraman | 2020-06-02 16:39

Hi! Just here to say I found a way to solve the error. Your code is perfect, but it works better if it’s inside the Script of the Node2D instead of player’s. The reason is that the position that the code receive is relative to the parent node (that should be the Node2D in this case). Anyway, if someone is making a fighting game and needs the code here it goes =)

func _physics_process(delta):
look_at_enemy()

if \$Enemy.position.x > \$Player.position.x:
\$Enemy/AnimatedSprite.flip_h = true
\$Player/AnimatedSprite.flip_h = false
else:
\$Enemy/AnimatedSprite.flip_h = false
\$BaseballChar/AnimatedSprite.flip_h = true

The Node Tree

Node2D
Player (KinematicBody2D)
CollisionShape2D
Sprite
Player (KinematicBody2D)
CollisionShape2D2
Sprite2

migraman | 2020-06-11 03:48