Простой пример актёра libGDX scene2d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Player extends Actor {
public static final float WIDTH = 190;
public static final float HEIGHT = 100;
public static final int WALK_FRAMES = 21;
Vector2 velocity;
TextureRegion[] walkFrames;
Animation walkAnimation;
float walkAnimationSpeed = 0.5f;
float walkTime = 0;
public Player(float x, float y) {
setSize(Player.WIDTH, Player.HEIGHT);
setPosition(x, y);
load();
}
private void load() {
velocity = new Vector2(0, 0);
// Генерируем массив текстур для анимации
walkFrames = new TextureRegion[Player.WALK_FRAMES];
for (int i = 0; i < Player.WALK_FRAMES; ++i) {
String frame = String.format("%04d", i + 1);
Texture texture = new Texture(Gdx.files.internal("Player/Walk/Walk" + frame + ".png"));
walkFrames[i] = new TextureRegion(texture);
}
// Создаём анимацию
walkAnimation = new Animation(walkAnimationSpeed / Player.WALK_FRAMES, walkFrames);
}
@Override
public void act(float delta) {
// Движение по нажатии на экран
if (Gdx.input.isTouched() || walkTime > 0) {
setX(getX() + velocity.x + 100 * delta);
walkTime += delta;
if (walkTime > walkAnimationSpeed) walkTime = 0;
if (getX() > Gdx.graphics.getWidth()) setX(0);
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
// Рисуем игрока
batch.draw(walkAnimation.getKeyFrame(walkTime), getX(), getY(), getWidth(), getHeight());
}
}