0 votes

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!

asked Jun 2 in Engine by migraman (25 points)

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.

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

1 Answer

0 votes
Best answer

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:

onready var enemy_pos = get_parent().get_node("Enemy").position

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:

onready var player_pos = get_parent().get_node("Player").position


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 :)

answered Jun 2 by drorya (144 points)
selected Jun 2 by migraman

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

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
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.