0 votes

I know this is a very simple question but I'm new to vectors and calculating them so I just get confused.

I have an NPC scene with AnimationSprite that has four animations: up, down, left, right and I have a player that I want to basically turn the NPC towards (by playing correct animation). I have both NPC position and player position and I just can't figure out how to calculate whether the player is on the right, left, above or below and I don't want to just make dozen if statements. So how do I calculate that? I know the answer is right there and it's very simple I just can't visualise it.

Godot version 3.5.stable
in Engine by (62 points)

2 Answers

0 votes
Best answer

I solved it by making Idle animation for the NPC with animationPlayer instead, and just input (player_position - npc_position).normalized() as vector for animationTree.

by (62 points)
0 votes

Try the following and you can replace global_transform.origin with position the former is used to show interchangeability with 3D

var animations = {
    Vector2.UP : "up",
    Vector2.DOWN : "down",
    Vector2.LEFT : "left",
    Vector2.RIGHT : "right"
}

func face_player():
    var origin = $Player.global_transform.origin - global_transform.origin
    var animation = "idle" # default animation
    var distance = 100 # default distance

    for face in animations:
        if origin.distance_to(face) < distance:
            #update distance to the lowest value
            distance = origin.distance_to(face)

            # choose animation
            animation = animations[face]

    $AnimatedSprite.play(animation)

For some reason just know there's an easier way, can practically feel it in my bones yet this is all that comes to mind right now.

by (5,808 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 Frequently asked questions and 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 [email protected] with your username.