2d enemy flipping script

Godot Version

4.4

Question

Hello again, I’ve run into this problem well for me it’s a problem, where I created an enemy which follows the player on the x axis but when the player jumps over it I want it to flip, to face it but did that for the animation player but don’t know how to make the collision shape flip too, I’ve been searching online for an answer for hours


Here’s my enemy script:
“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”“”‘’“”
extends CharacterBody2D

@onready var anima = $AnimatedSprite2D
@export var health = 20
@export var target = Node2D
var speed= 50
func _physics_process(delta: float) → void:
var direction_x = (target.position.x - position.x)

if direction_x == 0:
	velocity = Vector2.ZERO
else:
	velocity.x = sign(direction_x) * speed
	velocity.y = 0  # Make sure no vertical movement
anima.play("default")
move_and_slide()

func take_damage():
health -= 2
if health <= 0:
queue_free()
“”“”“”“”“”“”“”“”
Thanks

1 Like
  • Add a check to determine if enemy is facing left or right ( perhaps, is velocity.x greater or less than 0 )
  • Then use negative scale.x for the enemy’s Node2d ( sprite, or root node2d node )
  • If facing right, use 1.0 for scale.x
  • If facing left, use -1.0 for scale.x

You can see the flip / flop if you go into inspector → Transform → Scale and then see what happens if you play with turning those numbers negative

Hope this helps, thanks

1 Like