# How do I make a puzzle piece move smoothly between locations?

I'm building a 2048 clone to sharpen my Libgdx skills, but I don't know how to ease a tiles between board locations. When I slide my finger, the tile moves rather swiftly. How I can make the movement smoother?

This is the code I'm using to make it move to the left:

 for(float t=0;t<getMax(currentTile);t++
{
shapeRenderer.begin(ShapeType.Filled);
shapeRenderer.setColor(230/255.0f, 220/255.0f, 230/255.0f, 1);
shapeRenderer.rect(q-t, r, a, b);
shapeRenderer.end();
}


At the moment, you're moving the piece with a linear interpolation.

That means that every timestep, the tile's position changes by the same amount.

position = position + translation * timestep


You could use any function there:

position = position + translation * f(timestep)


Then the position changes by an amount determined by the function f.

There are a bunch of easing functions that people have found to work well for producing smooth transitions.

Robert Penner maintains implementations in various languages. Expo out and expo in-out are quite pleasant for puzzle pieces, though you might want to try elastic in-out for a stretchier, more playful effect.

The original 2048 seems to interpolate linearly between positions though.

Just to expand on Anko's answer - Easing functions are great, but they aren't necessary in every situation. Although not really initially meant for this purpose, Linear interpolation can also be used to create a simple easing effect, you simply have to call your interpolation function every frame with the same fraction given.

Think about it like this: your object will move half of the distance to the destination, then half of the new distance the next frame, and so on, until it reaches its destination (or approximates it well enough). This is a quick and easy way to approximate an easeOut function in what's essentially a single line of code.

I'm going to paste my own Lerp function and how I call it to achieve this effect, but with a bit of searching you can find a bunch of different ways to achieve the same thing.

float Lerp(float a, float b, float fraction)
{
return (a * (1.0f - fraction)) + (b * fraction);
}


This is how I call the function every time the game updates:

playerVelocity.x = Omega2D::Lerp(playerVelocity.x, 0.0f, 0.2f);


Though my example uses the function to decrease my player's velocity vector on one axis, the way you'd use it to change positions is identical. Essentially, you're telling it to change your value to 0.0f, and to move 0.2f of the distance every frame. The higher the fraction (0.2f) is, the 'faster' your movement will seem.

• ill definitely try it!!! May 7, 2014 at 13:13