• 2D
  • KinematicBody2D flip_h problem

Hello everybody. I know that this topic is often rolled up, but I have already watched a lot of tutorials, and searched the forum and I can not flip horizontal my "AnimatedSprite" when moving left.

https://pastebin.pl/view/3e72f4f2 - this is script from docs, I've tried to rewrite it in various ways but I still get errors :(

I found it working, but unfortunately I can't quite add gravity and jump to it:

https://pastebin.pl/view/6d6343cc

I only took a brief look at the script, but something like the following should fix the flip_h issue and add gravity/jumping:

extends KinematicBody2D

const GRAVITY = -100
const JUMP_SPEED = 300	
const SPEED = 750
var velocity = Vector2()
var movement = Vector2()

func _physics_process(delta):
	var direction = Vector2(0, 0)
	
	if Input.is_action_pressed("ui_right"):
		direction.x += 1
		$AnimatedSprite.play("run")
	
	if Input.is_action_pressed("ui_left"):
		direction.x += -1
		$AnimatedSprite.play("run")
	
	if Input.is_action_pressed("ui_up"):
		velocity.y += JUMP_SPEED
		$AnimatedSprite.play("jump")
	
	if direction == Vector2(0, 0): # Is still
		$AnimatedSprite.play("idle")
	
	# Flip the sprite so it looks in the correct direction
	if direction.x > 0:
		$AnimatedSprite.flip_h = false
	elif direction.x < 0:
		$AnimatedSprite.flip_h = true
	
	velocity += movement * SPEED
	velocity = move_and_slide(movement)

I have not tested the code, but I think it should work. (Side note: welcome to the forums!)

Thank you for your answer!

Hmm I can rotate the character, but the character does not move - it only rotates in place.

My bad, I forgot to replace a variable in the code. Replace line 34 with the following: velocity = move_and_slide(velocity) and then it should work. The issue before was that it was using movement in move_and_slide instead of velocity, leading to the character moving at 1 pixel a second. Sorry about that.


Looking at the code again, it might need acceleration and deceleration too, otherwise the player might end up "sliding" around as if they are on ice. The easiest way to handle this is set velocity.x to zero right after direction is defined, which should make it where the character does not slide around.