I am new to Slick2D and I am trying movements with my character. I can make it move smoothly while holding movement key, but I also want the character to finish its movement so it stops exactly on the next tile (I have simple map with tiles 32x32). And that is a problem for me, because it moves to the next tiles, but it teleports there - the movement is instant and I want my character to just continue with its movement with the same speed.
I tried for example something like this in my update()
method:
else if (input.isKeyPressed(Input.KEY_D))
{
characterAnimation = characterAnimationRight;
characterAnimation.update(delta);
xCoord = (int) xCoord;
while (xCoord%32 != 0)
{
xCoord += 1;
characterAnimation.update(delta);
if (xCoord > Window.WIDTH - 32)
{
xCoord = Window.WIDTH - 32;
}
}
}
but I can´t make it work.
The solution is not to calculate xCoord
in while()
in the update()
method. The reason is that it is calculated in single run of update()
method and after that the render()
method is called to render the character. That means character is rendered after that while()
and it teleports.
Here is my solution:
@Override
public void update(GameContainer gc, StateBasedGame s, int delta)
throws SlickException {
// .......
if (moving)
{
if (movingDirection == DIR_RIGHT)
{
if (xCoord >= targetCoord)
{
xCoord = targetCoord;
moving = false;
}
else
{
xCoord += delta * 0.1f;
characterAnimation.update(delta);
if (xCoord > Window.WIDTH - 32)
{
xCoord = Window.WIDTH - 32;
}
}
}
else if (movingDirection == DIR_LEFT)
{
if (xCoord <= targetCoord)
{
xCoord = targetCoord;
moving = false;
}
else
{
xCoord -= delta * 0.1f;
characterAnimation.update(delta);
if (xCoord < 0)
{
xCoord = 0;
}
}
}
else if (movingDirection == DIR_UP)
{
if (yCoord <= targetCoord)
{
yCoord = targetCoord;
moving = false;
}
else
{
yCoord -= delta * 0.1f;
characterAnimation.update(delta);
if (yCoord < 0)
{
yCoord = 0;
}
}
}
else if (movingDirection == DIR_DOWN)
{
if (yCoord >= targetCoord)
{
yCoord = targetCoord;
moving = false;
}
else
{
yCoord += delta * 0.1f;
characterAnimation.update(delta);
if (yCoord > Window.WIDTH - 32)
{
yCoord = Window.WIDTH - 32;
}
}
}
}
}
Variable moving
is set true after pressing movement key. Now after every call of render()
the character is moved a little bit in the update()
and rendered at this new position until it is exactly on the tile.