Making a sprite move.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bunnybot5555
:warning: Old Version Published before Godot 3 was released.

Hi,I want to make a sprite move when you press a key and don’t know how to do it.

:bust_in_silhouette: Reply From: DriNeo

Hi.
You need Node2D methods and Input methods. Check the docs.

As an example, I made this script quickly.

extends Sprite

var speed = 100
var vel = Vector2()


func _ready():
	set_process(true)


func _process(delta):
	if Input.is_key_pressed(KEY_RIGHT):
		vel = Vector2(speed, 0)
	elif Input.is_key_pressed(KEY_LEFT):
		vel = Vector2(-speed, 0)
	elif Input.is_key_pressed(KEY_UP):
		vel = Vector2(0, -speed)
	elif Input.is_key_pressed(KEY_DOWN):
		vel = Vector2(0, speed)
	else:
		vel = Vector2(0, 0)

	set_pos(get_pos() + vel * delta)

That still didn’t work. I have something using the same keycodes do you think that would affect it?

bunnybot5555 | 2016-09-27 22:21

Copy-pasting the example straight in a new scene works for me. I can control a sprite with the arrow keys.
Did you properly set the position of your sprite with set_pos after determining the movement (vel)?

Zylann | 2016-09-27 23:44

@bunnybot.
I believed you hadn’t started a project yet. You need to give more informations.
Where do you use theses keycodes ?
Have you received error messages in the debugging tab ?
Did you attach the script, as is, to the sprite ? Or have you pasted it into another script ?

DriNeo | 2016-09-28 08:42

Yay it worked but is it possible to make the sprite invisible until something is pressed?

bunnybot5555 | 2016-09-28 11:30

And also to just make it keep increasing even once you’ve let go of the ky

bunnybot5555 | 2016-09-28 11:54

If you have other questions, I suggest you ask them in a new thread, so people can see them directly rather than having to search in a comment of an unrelated thread.

Zylann | 2016-09-28 18:26