0 votes

I need to know if a sprite is moving up, left, down or right as it moves through a Path2D/Curve2d. I have different animations for each direction.

Thanks.

Godot version 3.3.2
in Engine by (61 points)

1 Answer

0 votes

One solution would be to store the global position the object was in during the last call to _process() or _physics_process(). You could get the difference of the current global position and the previous to get a vector for the change in position, and use its value to determine which animation you want to use.

The code below could be a starting point for this approach. This code doesn't account for x or y of the change in position being exactly zero; that's something you'd need to decide how to handle in your own implementation.

var last_position

func _ready():
    last_position = global_position

func _process(delta):
    var animation = get_animation_for(last_position - global_position)

    # any other code in _process()
    last_position = global_position

func get_animation_for(direction: Vector2):
    # moving left
    if direction.x < 0 and abs(direction.x) > abs(direction.y):
        return left_animation

    # moving right
    if direction.x > 0 and abs(direction.x) > abs(direction.y):
        return right_animation

    # moving up
    if direction.y < 0 and abs(direction.y) > abs(direction.x):
        return up_animation

    # moving down
    if direction.y > 0 and abs(direction.y) > abs(direction.x):
        return down_animation

Hope this helps!
-Skel

by (93 points)
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.