Flipping the sprite when changing directions.
2 Likes
Here’s what I did. Using numeric constants for direction helped with my code:
extends KinematicBody2D
# units are pixels for changing the location of objects on screen
const SPEED = 750
# movement directions
const LEFT = -1
const RIGHT = 1
const STILL = 0
# when the player moves this variable changes
var motion = Vector2()
# processes the physics engine every frame
func _physics_process(delta):
# get input and set movement
var direction = STILL
if Input.is_action_pressed("ui_right"):
direction += RIGHT
if Input.is_action_pressed("ui_left"):
direction += LEFT
motion.x = SPEED * direction
# animate based on the movement
if direction == STILL:
$AnimatedSprite.play("idle")
else:
$AnimatedSprite.play("run")
# flip the sprite only when direction is left, when still or right set to not flipped
$AnimatedSprite.flip_h = (direction == LEFT)
# apply movement to the player
move_and_slide(motion)
3 Likes
const SPEED = 750
var motion = Vector2()
func _physics_process(delta):
if Input.is_action_pressed("ui_right") and not Input.is_action_pressed("ui_left"):
motion.x = SPEED #player goes to the right
$AnimatedSprite.play("run")
$AnimatedSprite.flip_h = false
elif Input.is_action_pressed("ui_left") and not Input.is_action_pressed("ui_right"):
motion.x = -SPEED #player goes to the left negative speed
$AnimatedSprite.play("run")
$AnimatedSprite.flip_h = true
else:
motion.x = 0 #no movement
$AnimatedSprite.play("idle")
$AnimatedSprite.flip_h = false
move_and_slide(motion)```
Start ahead for now. keeping it simple. I like the const used by the others but leave that for later.
This code also handles jumping animation.
extends KinematicBody2D
enum Directions {STILL, RIGHT, LEFT = -1, UP = -1}
const SPEED = 750
var movement = Vector2()
func _physics_process(delta):
var direction = Vector2(Directions.STILL, 0)
if Input.is_action_pressed("ui_right"):
direction.x += Directions.RIGHT
$AnimatedSprite.play("run")
if Input.is_action_pressed("ui_left"):
direction.x += Directions.LEFT
$AnimatedSprite.play("run")
if Input.is_action_pressed("ui_up"):
direction.y += Directions.UP
$AnimatedSprite.play("jump")
if direction == Vector2(0, 0): # Is still
$AnimatedSprite.play("idle")
# Flip the sprite when going left
$AnimatedSprite.flip_h = (direction.x == Directions.LEFT)
movement.x = SPEED * direction.x
move_and_slide(movement)
I did it without flip_h
extends KinematicBody2D
const SPEED = 750
var motion = Vector2()
func _physics_process(delta):
if Input.is_action_pressed("ui_right") and not Input.is_action_pressed("ui_left"):
motion.x = SPEED
$AnimatedSprite.scale.x = 1 # instead of flip_h
$AnimatedSprite.play("run")
elif Input.is_action_pressed("ui_left") and not Input.is_action_pressed("ui_right"):
motion.x = -SPEED
$AnimatedSprite.scale.x = -1 # instead of flip_h
$AnimatedSprite.play("run")
else:
motion.x = 0
$AnimatedSprite.play("idle")
move_and_slide(motion)