Move a sprite with animation

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CKO

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”?

:bust_in_silhouette: Reply From: Eric Ellingson

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

(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

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?

CKO | 2019-02-18 08:14

It works perfectly. Thanks again.

CKO | 2019-02-18 08:31