Thursday, March 28, 2019

15. Tween

Any property can be animated by the Tween node. To a Node, we attach a script to animate the scale property of the sprite if either up arrow is pressed or down arrow is pressed.


In the _process function, we see if up or down have just been pressed. If they are, we either start the scale up animation or scale down animation. However we only start if no animations are running.


We create Sprite Node and two Tween nodes using new(). Then this script keeps monitoring for input to start animation:



extends Node

var sprite = Sprite.new()
var tween_up = Tween.new()
var tween_down = Tween.new()

func _ready():
    sprite.texture = load("res://icon.png")
    sprite.position = Vector2(100, 100)
    add_child(sprite)
    add_child(tween_up)
    add_child(tween_down)
 
func _process(delta):
    var up = Input.is_action_just_pressed("ui_up")
    var down = Input.is_action_just_pressed("ui_down")
    if (up or down) and (tween_up.is_active() or tween_down.is_active()):
        print('Please wait ...')
    elif up:
        print('up')
        tween_up.interpolate_property(sprite, 'scale',
            Vector2(1.0, 1.0), Vector2(2.0, 2.0), 2,
            Tween.TRANS_CIRC, Tween.EASE_OUT)
        tween_up.interpolate_property(sprite, 'scale', 
            Vector2(2.0, 2.0), Vector2(1.0, 1.0), 2,
            Tween.TRANS_QUAD, Tween.EASE_IN, 2)
        tween_up.start()
    elif down:
        print('down')
        tween_down.interpolate_property(sprite, 'scale',
            Vector2(1.0, 1.0), Vector2(0.5, 0.5), 2,
            Tween.TRANS_CUBIC, Tween.EASE_OUT)
        tween_down.interpolate_property(sprite, 'scale',
            Vector2(0.5, 0.5), Vector2(1.0, 1.0), 2,
            Tween.TRANS_QUAD, Tween.EASE_IN, 2)
        tween_down.start()


We can refactor a lot of code into separate functions for ease of reading and developing bug-free code. It will not be a good idea to put everything in the main loop, _process, but we should put them in separate functions.


The output during a scale up animation, with the project window size of 200 by 200:


No comments:

Post a Comment