Moving Sprite2d

Godot Version

4.3

Question

Hello,

I have a Sprite2D object that I want to move when a button is pressed. I was trying to do this through Transform2D, but that does not seem to move my sprite when I press the button.

If I have Transform2D in the _ready() function that it will move once, and I was able to verify that I am getting to this code by adding a print statement in my move() function.

I’m basically looking for a way to move a Sprite2D object, no animation or collision needed. In a sense I just want a sprite teleported to a part of the screen when a button is pressed. Please let me know if you have any suggestions.

Thanks!

func _on_rice_pressed() → void:
rice.move()
pass # Replace with function body.

func move() → void:
Transform2D(0,Vector2(200,200))
pass

Your syntax isnt quite right. You can always go to the Godot Docs (Godot Docs – 4.3 branch — Godot Engine (stable) documentation in English) and lookup Transform2D, or anything, to see the methods/properties and usually some code examples

Here is the correct code:

# Move the sprite when the button is pressed
func _on_rice_pressed() -> void:
    rice.move()

# Function to move the sprite
func move() -> void:
    # Set the position of the sprite to the desired coordinates
    position = Vector2(200, 200)

Sadly I have tried that and it doesn’t work. I started out by using position = Vector2D(200,200) but when that wasn’t working I tried to understand how Transform2D works, since I wasn’t able to get it working with Vector2D.

To give more details, I have a main script with the object rice created in it, that rice object has the method move(). The script with move() is attached to a Sprite2D node.

Yes, sorry i forgot a key piece. You have to reference the object you want to move.
If the script is on the object itself then this should work:

self.position = Vector2(200,200)

The script is on the object, but self.position did not work either.