0 votes

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 moveright line is above than moveleft 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

in Engine by (17 points)

1 Answer

0 votes

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!

by (392 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.