+1 vote

What is the best way to manage flipping a character from left to right and so on? For example, you have a character with a collision shape, sprite, and area2d with collision shape to detect sword swings. How would you approach flipping this character to the left side and back to the right? I find that doing each separate node and flipping it with

node.position.x = direction * HARDCODED DISTANCE 

The hardcoded distance part is what disturbs me, when I have a area2D that is positioned like 2 on the x and 0 on y, to flip it I have to hard code direction * 2 to always keep it the same distance. How do you handle flipping nodes and flipping all of the hit boxes areas and everything to flip with it? Anyway to avoid hardcoding values?
2D, 2 directions, left and right

https://imgur.com/a/VF37Mdo

asked Mar 22 in Engine by Nikola-Milovic (37 points)

1 Answer

+2 votes
Best answer

You can invert the scale-property of the root-node in your character-scene. Instead of using Vector2(1, 1) you can use Vector2(-1, 1) to flip it horizontally or Vector2(1, -1) to flip it vertically. Of course doing both at once is also possible.

answered Mar 23 by njamster (9,950 points)
selected Mar 23 by Nikola-Milovic

Thank you but I wouldnt have posted a question if I hadn't tried everything. This doesnt work. It flips the character on the x and y axis randomly.
https://imgur.com/a/Oc4f1oS

I also tried just the scale.x, position, I tried 20 fixes and ideas from guys over at discord and nothing, absolutely nothing has worked.

This does work! However, not for physics bodies, see this issue.

That same issue mentions a "fix" for your problem in the end:

scale.x = scale.y * direction

However, I don't fully understand why this works, so I'd recommend sticking with Zylann's advice of only adjusting the scale for visual nodes (e.g. a Sprite) instead. So something like this should work and not required any HARDCODED DISTANCE:

func change_dir(dir):
if look_at != direction:
    $CollisionShape2D.position.x *= -1
    look_at = direction
    $Sprite.scale.y = direction

Yeyyy, finally. I would've never guessed that this works the way it does.... Thanks a lot. It's properly working now.

You are a genius
Thank you!

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.