How to best do movement in 8 directions in 2d?

Godot Verion

4

Question

I made a code for movement in 8 directions in 2d. but I did it when I was just starting and a doubt arose, Is it optimal to use AnimatedSprite2d in this way? calling it on each input that is executed or is it easier with the AnimationTree?

const SPEED = 10

func _physics_process(_delta):
		

	var velocity = Vector2(0,0)
	
	if Input.is_action_pressed("ui_up") and Input.is_action_pressed("ui_right"):
		velocity.x += 1
		velocity.y -= 1
		$AnimatedSprite2d.play("walk up right") #diagonal move
		
	elif Input.is_action_pressed("ui_up") and Input.is_action_pressed("ui_left"):
		velocity.x -= 1
		velocity.y -= 1
		$AnimatedSprite2d.play("walk left up") #diagonal move
		
	elif Input.is_action_pressed("ui_left") and Input.is_action_pressed("ui_down"):
		velocity.x -= 1
		velocity.y += 1
		$AnimatedSprite2d.play("walk down left") #diagonal move
		
	elif Input.is_action_pressed("ui_right") and Input.is_action_pressed("ui_down"):
		velocity.x += 1
		velocity.y += 1
		$AnimatedSprite2d.play("walk right down") #diagonal move
		
	elif Input.is_action_pressed("ui_right"):
		velocity.x += 1
		$AnimatedSprite2d.play("walk right")
		
	elif Input.is_action_pressed("ui_down"):
		velocity.y += 1
		$AnimatedSprite2dplay("walk down")
		
	elif Input.is_action_pressed("ui_down"):
		velocity.y += 1
		$AnimatedSprite2d.play("walk down")
	
	elif Input.is_action_pressed("ui_left"):
		velocity.x -= 1
		$AnimatedSprite2d.play("walk left")
	
	elif Input.is_action_pressed("ui_up"):
		velocity.y -= 1
		$AnimatedSprite2d.play("walk up")
	
	if velocity.length() > 0:
		velocity = velocity.normalized() * SPEED
		move_and_collide(velocity)
	
	else:
		$AnimatedSprite2d.play("idle")
velocity = Input.get_vector("ui_left","ui_right","ui_up","ui_down")

I would then use a blend tree animation tree player node to use the velocity variable to select an animation.

Skip to about 8:50 to see what I mean.

You would use the velocity variable to set the blend position.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.