Area2D Move horizontal and vertical

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Alexandru Bâgu

Hey,

I’m a web developer which wants to learn more about Godot but I’m struggling with my initial project. Basically I want to move an Area2D only on x-y axis and create a Line2D to simulate the movement.

In order to do that I’ve create a Player Node (Area2D) with the following script attached:

extends Area2D

export var speed = 500
var target = Vector2()
var screen_size

func _ready():
	screen_size = get_parent().get_viewport_rect().size

func _input(event):
	if event is InputEventScreenTouch:
		target = event.position

func _process(delta):
	var velocity = Vector2()
	if position.distance_to(target) > 10:
		velocity = target - position

	if velocity.length() > 0:
		velocity = velocity.normalized() * speed
		
	
	position.x += velocity.x * delta
	if round(velocity.x) == 0:
		position.y += velocity.y * delta
		
	position.x = clamp(position.x, 0, screen_size.x)
	position.y = clamp(position.y, 0, screen_size.y)

Also I’ve attached a Line2D node with a script attached:

extends Line2D

func _process(delta):
	global_position = Vector2()
	if points.size() > 0:
		add_point(Vector2(points[-1].x, get_parent().global_position.y))
		add_point(get_parent().global_position)
	else: 
		add_point(get_parent().global_position)

The problem is the moment doesn’t have the same speed and also sometimes the Line2D stops drawing. I created a video to show what’s happening: YouTube Demo

I would be grateful if somebody can help me.
Thanks in advance