• Hey! Guest! The 40th (!!!) GMC Jam will take place between February 25th, 12:00 UTC to March 1st 12:00 UTC. Why not join in this very special anniversary jam! Click here to find out more!

GMS 2.3+ Problems with using image_xscale on a chasing enemy.

Enako_Inc

Member
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)
 

Enako_Inc

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)
Thank you this working perfectly.
 
Top