Problems with using image_xscale on a chasing enemy.

E

Enako_Inc

Guest
Hello, apologies if this is in the wrong place but I'm having a problem with the code I'm using to have enemies face the player character. Basically whats happening is if the enemy and the player character are sharing the same x position (e.g. directly above or below the player) the enemy sprite will endlessly flip its xscale. Here is my code:

GML:
//face player
if (instance_exists(obj_player))
{
var x_to_player = x - obj_player.x;
if (x_to_player != 0)
{
    image_xscale = -1 * sign(x_to_player);
}
}
 

DaveInDev

Member
you need some "hysteresis". Try something like

GML:
var x_to_player = x - obj_player.x;

if (abs(x_to_player) > 10 )
{
    image_xscale = -sign(x_to_player);
}
when very close to the object, the player will keep its last direction, and will not flip forever.

Change 10 to the value that suits your needs (depends on the size of your sprites)
 
E

Enako_Inc

Guest
you need some "hysteresis". Try something like

GML:
var x_to_player = x - obj_player.x;

if (abs(x_to_player) > 10 )
{
    image_xscale = -sign(x_to_player);
}
when very close to the object, the player will keep its last direction, and will not flip forever.

Change 10 to the value that suits your needs (depends on the size of your sprites)
Thank you this working perfectly.
 
Top