Jorj
Jorj

Reputation: 1301

Scale and transform in LibGDX

I have to do something like this in my Android App with LibGDX: enter image description here

The ball is a Image that has a drag listener and added to a Stage:

ballImage.addListener(new DragListener() {
  public void drag(InputEvent event, float x, float y, int pointer) {
    ballImage.moveBy(x - ballImage.getWidth() / 2, y - ballImage.getHeight() / 2);
  }
});

which works great. But I have a problem with scaling the ball. I can't scale the ball and maintain it's position and drag stop working normally (ball jump outside screen just on touch). I tried something like this:

massSlider.addListener(new ChangeListener() {
  public void changed (ChangeEvent event, Actor actor) {
    float x = ballImage.getX() - ballImage.getWidth() / 2;
    float y = ballImage.getY() - ballImage.getHeight() / 2;
    ballImage.moveBy(x, y);
    ballImage.setScale(massSlider.getValue());
    ballImage.moveBy(-x, -y);
  }
});

Also, I was trying to use scaleBy()/setScale() and moveBy()/setPosition(), or to not move the ball at all before and after scaling, but nothing seems to work. What I do wrong?

Upvotes: 1

Views: 413

Answers (1)

Xoppa
Xoppa

Reputation: 8123

Scaling is usually something that you want to (and easily can) avoid. It is nice to use scaling e.g. for actions to create a short pop out or pop in effect. But apart from that it's usually much better to adjust the size instead. So instead of using setScale(a) you do: setSize(a * unscaledWidth, a * unscaledHeight). Note that you will have to keep track of the unscaled width and height for this.

Upvotes: 2

Related Questions