perfect move_and_slide to both directions

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By cenka

Hello ,
I just encauntered a small issue.
all I want is perfect movements to the right and to the left.
for example with this code

func _process(delta):

if Input.is_action_pressed("move_right"):
	velocity.x = speed
if Input.is_action_just_released("move_right"):
	velocity.x = 0

if Input.is_action_pressed("move_left"):
	velocity.x = -speed
if Input.is_action_just_released("move_left"):
	velocity.x = 0	
velocity = move_and_slide(velocity,UP)

I know its not perfect but I playing around with godot and realized that with this code you can go to the right when holding “D” so if i holding “D” im moving to the right and if im also pressing “A” while holding “D” its moves to the left perfectly even if im holding “D” but the same trick doesnt work when im holding “A” and sometimes pressing “D” .
in simpplier words all I want is to create perfect moving sistem that when last key was pressed to move no matter if you holding another key which should mvoe you to the oposite direction it will execute the last button and his command.

In fact i know that there is a problem with my if statments and if move_right line is above than move_left it wont execute the same ways in both directions .

but what im asking is there are more advanced way to do those things or should I create my own if else statments code in which i will check every interaction and in result get the last thing you pressed no matter if you holding other keys and etc.

sorry english isnt my first language so I hope you guys get the meaning of what i tryed to ask .
have a great day

:bust_in_silhouette: Reply From: RedBlueCarrots

Try:

func _process(delta):
    velocity.x = 0
    if Input.is_action_pressed("move_right"):
        velocity.x += speed
    if Input.is_action_pressed("move_left"):
        velocity.x -= speed  
    velocity = move_and_slide(velocity,UP)

This should work unless you are trying to alter velocity.x somewhere else in your code later on, but in that case just create a new variable to represent your input direction and work from there.

Hope this helps!