GMS 2 How to change sprites

I

iScream

Guest
So I want to make a sprite change based on mouse_x and mouse_y , so when mouse_x is less than object's x, then the sprite changes to this one which is turned left, and the same thing with y value. I have this line of code:

if (x < mouse_x) sprite_index = spr_playerR;
if (x > mouse_x) sprite_index = spr_playerL;


which works fine, but I don't know how to make that sprite changes in x and y at the same time. I tried

if (y < mouse_y) sprite_index = spr_playerD;
if (y > mouse_y) sprite_index = spr_playerU;


But it glitches :/
(R=right, L=left, etc...)
What commands should I use?
I am sooo novice, so I need an explanation.
 

Bentley

Member
ut I don't know how to make that sprite changes in x and y at the same time.
Do you mean that you have spr_up_right, spr_bot_left, etc. sprites?

If so, off the top of my head
Code:
dir_x = sign(mouse_x - x);
dir_y = sign(mouse_y - y);
dir_to_mouse = point_direction(0, 0, dir_x, dir_y);
switch (dir_to_mouse)
{
    case 0: sprite_index = spr_right; break;
    case 45: sprite_index = spr_up_right; break;
    //etc.
}
 
I

iScream

Guest
Do you mean that you have spr_up_right, spr_bot_left, etc. sprites?
No, I have sprites spr_up, spr_down, spr_left and spr_right, and I want to change them to point the arrow, but not by using image_angle = point_direction(x, y, mouse_x, mouse_y); but by changing sprites.
I don't know if I explained clearly so there is a video I uploaded to YouTube:
 

Guitarmike

Member
if (x < mouse_x) sprite_index = spr_playerR;
if (x > mouse_x) sprite_index = spr_playerL;

if (y < mouse_y) sprite_index = spr_playerD;
if (y > mouse_y) sprite_index = spr_playerU;


Two of these conditions can be true at any time, i.e. x<mouse_x AND y > mouse_y. But your object can only store one value in sprite_index. So whichever condition is checked last (in my example, y >mouse_y) will be the one that ultimately decides which sprite is displayed. You either need to create four additional sprites where the character is facing up/left, up/right, down/left, and down/right or create some logic that somehow dictates that only one of the four states can be true at any time.
 

Bentley

Member
You can set the sprite based on what direction cone the mouse is in. So using my above code:

Code:
if (dir_to_mouse >= 225 && dir_to_mouse <= 45)
{
    sprite_index = spr_right;
}
 
Top