Snake
2 Adding The Snake Body

Section Menu

Snake Home | 1 | 2 | 3 | 4 | 5

Making a snake body that follows the head is a bit trickier than you might think. This is going to require us to do some scripting.

Start by opening up the room and going to the Settings section and change the room speed to 5. This means that there will be 5 steps of the game every second.

Create Event

Return to the snake head object window and find the Create Event that you made earlier. Delete the Move Fixed action, this will not be needed any more.

Add an Execute Code action to the Create Event. A window pops up to allow you to type in some code. The following code should be entered here,

global.parts[0]:=id;
global.numparts:=0;
alarm[0]:=1;

The first line sets up a global variable to store the details of the snake body. The second line sets up another variable to store the number of parts that the snake has. The last line sets the Alarm 0 to go off in 1 step.

Alarm 0 Event

The alarm is used to add body parts to the snake head. The following code needs to be executed in this event.

newb:=instance_create(global.parts[global.numparts].x, global.parts[global.numparts].y,obj_body);
newb.number:=global.numparts+1;
global.numparts+=1;
global.parts[global.numparts]:=newb;
if global.numparts<4 then alarm[0]:=1;

The first line creates a new instance of the body object in the location where the last item currently is. The second line records the id number of the new instance. Line 3 turns the new instance into the last body part. The final line sets the alarm again to make sure that there are enough parts to the snake.

Step Event

The step event is used to move the head along one section of the grid.

x:=x+lengthdir_x(16,direction);
y:=y+lengthdir_y(16,direction);
with obj_body
{
x:=global.parts[number-1].xprevious;
y:=global.parts[number-1].yprevious;
}

The first two lines move the snake head 16 pixels in the direction in which it is currently facing. Both the x and y coordinates of the instance need to be moved. The next line tells Game Maker that the lines between the curly braces { } will be applied to the obj_body instances. The lines within the curly braces move each item in the parts list to the previous position of the item one lower in the list. This creates the effect of the body objects following the head.

⇐ Previous | Next ⇒