• Hey! Guest! The 37th GMC Jam will take place between May 28th, 12:00 UTC and June 1st, 12:00 UTC. Why not join in! Click here to find out more!

GMS 2 [SOLVED] Need Help with Sprite Directions

T2008

Member
I am trying to make the NPCs face player when player is talking to npc. I made the below script that I run which does 4 diagonal directions. I can't get it to work for all 8 directions. I use the switch statments with all 8 when objects are moving (like enemies). However this doesn't work when enemy/character is not moving. Any help would be greatly appreciated!

Current Script:
Code:
//Player Left and Above NW
if (obj_player.x < x) && (obj_player.y < y) {
    sprite_index = stand_nw; 
    npc_stopped_sprite = stand_nw;
}
//Player Left or Equal and Below or Equal SW
if (obj_player.x <= x) && (obj_player.y >= y) {
    sprite_index = stand_sw;
    npc_stopped_sprite = stand_sw;
}
//Player Right and Above NE
if (obj_player.x > x) && (obj_player.y < y) {
    sprite_index = stand_ne; 
    npc_stopped_sprite = stand_ne;
}
//Player Right or Equal and Below or Equal SE
if (obj_player.x >= x) && (obj_player.y >= y) {
    sprite_index = stand_se;
    npc_stopped_sprite = stand_se;
}

Script that works only when object is moving:
Code:
switch ((((direction + 22.5) mod 360) + 360) mod 360) div 45 {
    case 0: sprite_index = choose(stand_e,eat_e); break;
    case 1: sprite_index = choose(stand_ne,eat_ne); break;
    case 2: sprite_index = choose(stand_n,eat_n); break;
    case 3: sprite_index = choose(stand_nw,eat_nw); break;
    case 4: sprite_index = choose(stand_w,eat_w); break;
    case 5: sprite_index = choose(stand_sw,eat_sw); break;
    case 6: sprite_index = choose(stand_s,eat_s); break;
    case 7: sprite_index = choose(stand_se,eat_se); break;
}
 

TheouAegis

Member
Your problem is the player is prob never going to be at exactly the same x or y coordinate. He will always be a little bit off. You need to give a margin of error.

Typically, you take the direction to the player, divide it by 45 rounded off, then choose the sprite based on that.

point_direction(x,y,player.x,player.y) div 45
 

T2008

Member
Thanks for responding. What do I set direction as in the create event? Eg direction = 0 in create event? and this will automatically make character face player?

Edit: I tried the above code (setting direction to 0 in create event) and it didn't work. Any ideas?
 
Last edited:

TheouAegis

Member
Don't mess with the variable direction. And your code for setting the Sprite when you are moving, you see where you have the variable for direction? For standing still and facing the player, you replace direction with point_direction(x,y,player.x,player.y). The rest of your code is already in place.
 

T2008

Member
I tried what you said and it works perfectly!!!!! Thank you so much! You really helped me out a lot! It's always great when something works who it is supposed to.
 
Top