0 votes

I have the following code to move a sprite gradually from point a to b:

extends Sprite

var moveBy = null
var moveTo = null

func _process(delta):
    if moveTo != null:
        translate(Vector2(moveBy.x * delta, moveBy.y * delta))
        if position == moveTo:
            moveBy = null
            moveTo = null

func move(destination):
    moveTo = destination
    moveBy = destination - position

Is there a built-in way of doing this in Godot Engine? Possibly one that provides an ease-in/ease-out option for the "animation"?

in Engine by (93 points)
recategorized by

1 Answer

+1 vote
Best answer

I think what you want is likely a Tween

First, add a Tween node to your scene. Then something like this might work:

func move(destination):
    var _node = self
    var _property = "position"
    var _initial_value = self.position
    var _final_value = destination
    var _duration = 1 # in seconds
    var _transition_type = Tween.TRANS_LINEAR
    var _ease_type = Tween.EASE_IN_OUT
    $Tween.interpolate_property(
        _node,
        _property,
        _initial_value,
        _final_value,
        _duration,
        _transition_type,
        _ease_type
    )
   $Tween.start()

(I put the method arguments into variables for clarity, but obviously that might be a bit overkill in your actual code.)

If you need to know when it is finished, you can listen for the tween_completed signal:

func _ready():
    $Tween.connect("tween_completed", self, "_your_method_to_handle_move_completed")

func _your_method_to_handle_move_completed():
   # do whatever
by (1,612 points)
selected by

Thank you very much. I am reading up on tweens now. I will accept your answer once I make it work. In the meanwhile, if you have time, could you have a look at my other question that no one seems to be interested in?

https://godotengine.org/qa/40531/is-there-an-easy-way-to-merge-two-tilesets

It works perfectly. Thanks again.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.