I used single line if statements to help with readability and used a direction variable to x axis movement. I also had a debug print() line in there to help confirm it was working correctly.
3 Likes
Love your use of direction @bhindi1224 so I updated my code to use the same concept. I added some constants to enhance readability.
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
# apply movement to the player
move_and_slide(motion)
1 Like
So I made more adjustments to these above codes and introduced enums.
They are kind of groups of constants. Enums give constants values starting from 0 so you can use it like I did but you can also assign all values to constants manually.
extends KinematicBody2D
enum Directions {STILL, RIGHT, LEFT = -1, UP = -1}
const SPEED = 750
var movement = Vector2()
func _physics_process(delta):
var direction = Directions.STILL
if Input.is_action_pressed("ui_right"):
direction += Directions.RIGHT
if Input.is_action_pressed("ui_left"):
direction += Directions.LEFT
if Input.is_action_pressed("ui_up"):
pass
movement.x = SPEED * direction
move_and_slide(movement)