• Hey! Guest! The 39th GMC Jam will take place between November 26th, 12:00 UTC and November 30th, 12:00 UTC. Why not join in! Click here to find out more!

GMS 2 [SOLVED] Random Switch State, Idle - Wander

K

Kyle Conway

Guest
Hey everyone, I'm relatively new to game maker but have been watching a lot of tutorials and reading the forums bunch and have been able to solve all of my own problems until now.

Basically I have a zombie NPC, that switches between multiple states; idle, wander, alert, attack, etc. I was hoping to create a code that would allow it to switch between idle, and wander "randomly", I recently started over on the code with some new things I learned and although the concept I am trying to achieve worked in the previous version, its just not working now.

The code for the idle state is:
Code:
switch (state)
{
    case "idle":

    counter += 1;
    move_and_collide(0,0);
  
    //Transition Triggers
    if (counter >= room_speed * 2){
        var change = choose(0,1);
        switch(change){
            case 0: state = "wander"; counter -= 120; break;
            case 1: counter -= 120; break;
    }
    }
        break;

[INDENT]case "wander":[/INDENT]
    move_and_collide(2,0); 
    counter += 1;
    if (counter >= room_speed *2){
        var zchange = choose(0,1);
        switch(zchange){
            case 0: state = "idle"; counter -= 120; break;
            case 1: counter -= 120; break;
        }
    }
            break;
}
essentially after the the timer reaches 120, it switches from "idle" to "wander" like planned and he begins to move, however it never switches back.

Suggestions, corrections, and ideas welcome!
 

immortalx

Member
Here's a somewhat simpler way to accomplish that, without nested switch statements:
Code:
counter += 1;

if (counter >= room_speed * 2) {
    state = choose("idle", "wander");
    counter = 0;
}

switch(state)
{
    case "idle":
        move_and_collide(0,0);
    break;

    case "wander":
        move_and_collide(2,0);
    break;
}
 
K

Kyle Conway

Guest
Thank you very much for the reply, to be honest I think it may have been human error for my code not working. I heard game maker uses the same seed for random events when testing, and I think the code was just choosing wander over and over for a while. Eventually it began to switch back and forth. I added an additional idle to the choose statement I.e. choose (“idle”,”idle”,”wander”) and it is working fine now.

But thank you so much for the suggestion on the code, it has made everything a lot cleaner and much more efficient!
 
Top