Search code examples
javaandroidandroid-studiolibgdx

Sprite animation left to right, what should I choose? Dynamic or Kinematic?


I'm trying to make an animation with a Sprite image. The animation is a character that moves from left to right of the screen and then right to left non-stop (loop). How do I go about doing it? Should I assign the physics of the character (actor) dynamic or kinematic?


Solution

  • Basically a dynamic body is controlled via forces, whereas with a kinematic body you assign positions directly. Therefore a kinematic body is more what you want. The question then becomes whether you need collision detection for this character.

    Calculating the position of a character moving right-left can be done like:

    float x = t % (2 * width);
    if (x > width) x = 2 * width - x;
    

    Where t is the output of System.currentTimeMillis or equivalent. Or you could use TweenEngine for the same effect. The sprite can then be drawn like following:

    sprite.setX(x);
    sprite.draw(spriteBatch);