• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Legacy GM Snake - finding other instances of same object [SOLVED]

H

Hello_Mother_Leopard

Guest
Hello!

I'm trying to do my own version of Snake, I have watched and read a few tutorials but none uses a method that suits my needs, so I'd like to understand why mine doesn't work, and how I can make it work.

Basically it starts with 3 parts, Head (the head), Snake (a body part) and Tail (the tail).
To determine which sprite a part uses and and in which direction it goes I use a script that takes as arguments the part that's before and the one that's after.
The script works fine when running the game with the 3 basic parts but as soon as the snake grows, I get the error message "local variable prevSnake(100003, -2147483648) not set before reading it.".

The following code is in the Snake (or body part)'s Step event:

Code:
//Assigning a number to body parts
length = instance_number(Snake);

var i, j, prevSnake, nextSnake;
for (i = 1; i < length; i ++)
{
   body[i] = instance_find(Snake,i);
   body[i].number = i;
};

//If 1 body part
if (length == 1) scr_body_dir(Head, Tail);

//If more than 1 body part
if (length > 1)
{
    //Comparing positions
    for (j = 1; j < length; j ++)
    {
        if (body[j].number == number - 1) prevSnake = body[j];
        if (body[j].number == number + 1) nextSnake = body[j];
    };
  
    //First body part
    if (number == 1) scr_body_dir(Head, nextSnake);
  
    //Last body part
    if (number == length) scr_body_dir(prevSnake, Tail);
  
    //Intermediate body part
    if (number != 1) && (number != length) scr_body_dir(prevSnake, nextSnake);
};
I'm sure there are simpler (and functioning) ways to achieve that so any help to make it simpler would be appreciated. :D
Thanks in advance!
 

NazGhuL

NazTaiL
Whatever the code you use, the error means: variable prevSnake is not declared.
WHen you create a new object for a 'part' make sure that you declare prevSnake. Put it in the create event.
 
H

Hello_Mother_Leopard

Guest
Thanks for your reply (and sorry for my late reply)!

Yeah, I thought that because it's a local variable I didn't need to declare it at all after "var prevSnake".

I tried both adding "prevSnake = 0" in the "Comparing positions" for loop or making it an instance variable as you said and no more error messages. :D
 
Top