GML [SOLVED] Simple code to move object's x using for is not working

MartinK12

Member
I'm working in GMS2 on simple code than will move object 100px left when clicked and I want this move to be slow.
I don't want to use alarms and I think simple for should do it but it's not working - object is moving instantly to position = x - 100px, and I want to move it slowly.
Code:
if clicked

{
    for (i = 480; i > 0; i = i - 1)
    {
        x = x - 0.25;
    }
    clicked = false;
}
My understanding of this code is that it should take 480 steps and game is set to 60 steps so it should work for 8 seconds and not instantly. How to make this work without alarms?
 

Binsk

Member
No, a block of code will always be executed all at once. Your entire four loop is occurring before the sprite can be drawn again.

The step event (aka, ALL the code inside it) is fully executed once per step.

All this to say, hey rid of the foor loop and either use an alarm or write your own check (which will just act similar to an alarm).
 

chamaeleon

Member
I'm working in GMS2 on simple code than will move object 100px left when clicked and I want this move to be slow.
I don't want to use alarms and I think simple for should do it but it's not working - object is moving instantly to position = x - 100px, and I want to move it slowly.
Code:
if clicked

{
    for (i = 480; i > 0; i = i - 1)
    {
        x = x - 0.25;
    }
    clicked = false;
}
My understanding of this code is that it should take 480 steps and game is set to 60 steps so it should work for 8 seconds and not instantly. How to make this work without alarms?
Don't use for loops to try to stimulate passing of time or frames. Skip a loop in your code entirely and let the step event be your loop. Simply have a variable, perhaps called hspd, contain the distance you want to travel in one frame and add it to x. You may then want to add conditions to reset it to 0 when you do not want the object to move, and set it to a suitable value when you do.
 
Top