I have a class called "Spaceship" that extends Actor class. It is added to a group class. The group class is added to stage.
I want my spaceship to reappear at the left side of the screen when it disappears on the right side, including when only a portion of the spaceship has disappeared.
Here is the spaceship class:
class Spaceship extends Actor() {
Sprite sprite;
public Spaceship(Texture texture) {
sprite = new Sprite(texture);
sprite.setPosition(getX(), getY());
}
@Override
public void draw(Batch batch, float parentAlpha) {
sprite.setPosition(getX(), getY());
}
}
Here is the Group class:
class SpaceshipLayer extends Group {
Spaceship spaceship;
...
public void draw(Batch batch, float parentAlpha) {
if (isRightKeyPressed) {
spaceship.moveBy(5, 0);
if (spaceship.getX() > screenWidth) {
// No working properly
spaceship.setX(0);
}
}
}
}
Here is my main screen class:
class Main implements Screen {
SpaceshipLayer spaceshipLayer;
Stage stage;
public Main() {
stage = new Stage();
spaceshipLayer = new SpaceshipLayer();
stage.addActor(spaceshipLayer );
}
...
}
I am using actor coordinates for collision, etc. It is possible to do the horizontal scroll keeping sprite and actor values?
I am not sure if it is the best solution, but this is how I did it. I created an array of two spaceships with a distance difference between these two. So, when one of them disappeared to the right, the another one appears from the left.
class SpaceshipLayer extends Group {
Spaceship[] spaceships = new Spaceship[2];
public SpaceshipLayer() {
...
// set X at center of screen
spaceships[0].setX(getWidth / 2);
// spacesship location - screen width
spaceships[1].setX(spaceships[0].getX() - getWidth());
}
...
public void draw(Batch batch, float parentAlpha) {
if (isRightKeyPressed) {
for (Spaceship spaceship : spaceships) {
spaceship.moveBy(5, 0);
}
}
...
for (Spaceship spaceship : spaceships) {
...
if (spaceship.getX() > getWidth()) {
spaceship.setX(0 - spaceship.getWidth);
}
...
}
}
}