Sponsored By

Snake Ultimate - Dev Blog #1 - Smooth Movement in Unity3D

Today I show you how I achieved aesthetically pleasing grid-based movement in Snake Ultimate.

Chris Jenkins, Blogger

January 19, 2015

34 Min Read
Game Developer logo in a gray background | Game Developer

Snappy movement in arcade games are a big problem! It's aesthetically unpleasing today! 

So, I'm going to show you a super simple way to get your snake moving like its 2015. And the method I'm using for the mobile friendly, Snake Ultimate. 

 

 

 

 

Doing a smooth transition in Unity is easy with Vector.MoveTowards in your Update loop: 
 

 

float speed = 2.0f * Time.deltaTime; 


// move the head to its target location 

tail[0].transform.localPosition = Vector2.MoveTowards ( tail[0].transform.localPosition, targetPos, speed ); 


// move last tile to its target position 

if (tail.Count>0) { 

        int last = tail.Count-1; 

        tail[last].transform.localPosition = Vector2.MoveTowards ( 

                 tail[last].transform.localPosition, tail[last].targetPos, speed ); 

 

 

The target positions are aligned to the grid, so we're STILL snapping the snake to the grid but we're moving it slowly there first. When the head reaches the target position, we set a new position for the tail and the head (aka a tick). This new position is found by looking at the next tile on the grid in front of the head (depending on the direction) : 

 

// set the head's new target position
int targetRow = tail[0].row + dir.y; 

int targetCol = tail[0].col + dir.x; 
 
targetPos = new Vector2 ( targetCol * tileSize, targetRow * tileSize ); 

 
At each tick (which is when the head reaches its target position), the last tile of the snake is moved to the head's position:
 

// move the last tile to the head's position 

if (tail.Count > 0) { 

     tail[tail.Count - 1].transform.localPosition = tail[0].transform.localPosition; 

     tail.Insert(0, tail[tail.Count - 1]); 

     tail.RemoveAt(tail.Count - 1); 

}

 

 


 

You can also choose to use 2d Toolkit's Tiled Sprite to scale the front and end tiles instead of moving them. You'd need to rotate the tile or set an anchor point in the correct direction.

 

 

 

Read more about:

Blogs
Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like