How to make 2D Sprites Switch depending on Players view

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

My problem is mainly having NPC’s changing 2D sprites in a 3D space. What I want to obtain is how the NPC’s look in The Elder Scrolls I & II and have their sprites change depending on where i’m looking at them from. All I can think of is using a raycast on my player, but I’m fairly new to godot and programming and don’t quite understand how well I’d be able to do that. Anything helps, thank you.

do you mean you want the sprites to face you? I think you could use “look_at()”

Reddit - Dive into anything

ArthurER | 2020-10-07 13:47

:bust_in_silhouette: Reply From: miskotam

Assuming that your Player is facing its z-axis, and you know your Player’s and NPC’s position, you could calculate the angle like this:

var facing = transform.basis.z
var player_enemy_direction = player_pos.direction_to(npc_pos)
var direction_scalar = player_enemy_direction.dot(facing);

Where palyer_pos and npc_pos are global positions and they are normalized.

Based on the direction_scalar, you can change your NPC’s sprite.
The direction_scalar will be a number between -1 (180°) and 1 (0°) (if your positions are normalized)

It’s quite tricky. I would recommend you to check out Godot’s Vector math documentation