Game development live blogging - Part 2

Alright yesterday I left a body-less snake alone in Part 1.

Today I am going to make it attach with its body, and have you test-drive the snake in the editor, even in "Edit mode"... Fancy! I know, that's one of the strength's of Unity3d's editors.

Recap : So far, in the editor, edit mode, I am able to drag the snake's head GameObject, and snap it to the grid. Now its time to link them together.

Usually in the past, I always hold them all in a single array like data structure and keep updating their position using code, by shifting their position data from head to body 1, and body 1 to body 2 and so on. This time I am going to try a new approach. Let's do it the Unity3d's way.

First I am going to declare a new variable called "nextPart" of type SnakePart. I realised, each part's responsibility is only to pass its old position to the next body part. This will be a chain effect and the entire snake will move. Also we never use the body part's position in any snake game, except for to check collision between head and all of its body parts every time the head moves.

Added this line to SnakePart.cs script
public SnakePart nextPart;

Now the editor inspector looks like this

Now drag and drop, body1 to the next part. Do the same thing with body2 and drag and drop that GameObject onto body1's SnakePart script. Now the link is formed. For the sake of aesthetics, lets make more body links, by copy pasting the existing body parts. Highlight "body2"on the hierarchy window and pressed Cmd + D until I see body3, 4 and 5.

Now to drag them all as a snake, I need to pass the previousX and Y position to the nextPart of each SnakePart until nextPart is null. Also I am going to remove the code in Start() method, as I assume the snake body locations will be setup correctly in the beginning due the snapping feature.

So I introduce a new public method called SetSnakePosition(), and use it to set the position.
public void SetSnakePosition(int x, int y)
if (x != this.X || y != this.Y)
if (nextPart != null) nextPart.SetSnakePosition(this.X, this.Y);
this.X = x;
this.Y = y;
this.transform.localPosition = new Vector3(this.X * gridConverter, this.Y * gridConverter, 0);
The above code does two things, it updates the position of the linked snake part behind the current part & it sets the correct localPosition by converting grid co-ordinates into world co-ordinates using the gridConverter scaling value.

In next part we will do more exciting things in the snake and get it to move using the method we wrote above.


Popular posts from this blog

DoTween - The Big Demo

Download Android SDK standalone for offline installation

Setting up Visual Studio Code for Haxe Development - Hello World on Mac