New User: My if statements are bleeding together?

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

Hi! I’m new to godot and following a tutorial to make “Dodge the Creeps”.
However, while coding for movement my if statements are bleeding together, ie it catches the first if statement, and then ignores every proceeding one, executing their contents regardless. Any idea how to fix this? I only have experience in ASM and C++, so I’m still adjusting to differences in GDscript.

    extends Area2D

export var speed = 400.0 ;

func _process(delta):
	var direction = Vector2.ZERO
	if Input.is_action_pressed("move_right"): 
		direction.x += 2
	if Input.is_action_pressed("move_left"): 
		direction.x+= -2	
	#if Input.is_action_pressed("move_up"):
		#direction.y-=2
	#if Input.is_action_pressed("move_down"):
		#direction.y+=2
	#if direction.length()>1:
		#direction =direction.normalized();
		position += (direction*speed)*delta

Don’t go to conclusions without symptoms. What is happening in what did You expect to happen with this code ?

Inces | 2022-10-23 14:09

Basically you press the button (mapped in the input map), in this case W A S D, and your character moves an a direction based on direction, speed, and delta-time.

What is actually happening here is that pressing A (left) causes the player to move left correctly, but pressing D causes the player to move right and left at the same time, uncommenting the other lines makes movement more screwy, somehow only allowing diagonal movement.

I just don’t understand how I can separate these, or maybe there’s a better way to handle movement, I don’t know if Godot has a “case option” yet.

vAstra | 2022-10-23 15:06

:bust_in_silhouette: Reply From: vAstra

I fixed it by copying someone who copied it from the godot documentation and then tweaking it a little.

I don’t know why, but it works, so I’ll take it.

    extends Area2D

export (int) var speed = 200

var velocity = Vector2()

func get_input():
	velocity = Vector2()
	if Input.is_action_pressed('move_right'):
		velocity.x += 1
	if Input.is_action_pressed('move_left'):
		velocity.x -= 1
	if Input.is_action_pressed('move_down'):
		velocity.y += 1
	if Input.is_action_pressed('move_up'):
		velocity.y -= 1
	velocity = velocity.normalized()

func _physics_process(delta):
	get_input()
	position += velocity * speed * delta
:bust_in_silhouette: Reply From: Whom

In your original script you have indented position += (direction*speed)*delta one step too much so it is only executed when the if statement Input.is_action_pressed("move_left") is true. It should be executed regardless of input. Fixing the indentation makes the script work.