我有HorizontalGroup与演员添加到它。当我点击一个角色时,我希望它在屏幕中央弹出(伪代码)
Gdx.graphics.getWidth()/2 - myActor.getWidth()/2;
Gdx.graphics.getHeight()/2 - myActor.getHeight()/2;
问题是演员得到的位置是相对于父角色的,而不是舞台/屏幕。
我该如何着手解决这个问题?
有很多种可能来解决你的问题。
-
将屏幕坐标转换为舞台坐标(如果相同则跳过),然后将舞台坐标转换为组坐标,然后将演员设置为转换后的位置
vector = stage.screenToStageCoordinates(vector); vector = group.stageToLocalCoordinates(vector); actor.setPosition(vector.x, vector.y);
-
添加一个
Stack
到你的舞台,添加已经存在的组到它,然后如果你点击演员添加它到堆栈(这会自动从它的旧父)Stack stack = new Stack(); stage.addActor(stack); stack.add(yourGroup); // then on tap stack.add(actor);
-
禁用组布局,所以如果你操纵角色,组布局不会再次计算,加上禁用子变换到父坐标:
group.setLayoutEnabled(false); group.setTransform(false);
-
与2类似。,但将演员添加到舞台并将位置设置为中心
// then on tap stage.addActor(actor); actor.setPosition( (stage.getWidth() - actor.getWidth()) / 2f, (stage.getHeight() - actor.getHeight()) / 2f);
根据您的设置,一些解决方案可能不像预期的那样工作。
下面是一个例子:
public class TestGame extends ApplicationAdapter
{
private Skin skin;
private Stage stage;
private Texture t;
@Override
public void create()
{
skin = new Skin(Gdx.files.internal("uiskin.json"));
t = new Texture(Gdx.files.internal("badlogic.jpg"));
// So we see everything
stage = new Stage(new ExtendViewport(4000, 400));
HorizontalGroup hGroup = new HorizontalGroup();
hGroup.setFillParent(true);
// So that the hGroup is on top
Table filler = new Table(skin);
filler.setFillParent(true);
filler.add(hGroup).fill().center();
stage.addActor(filler);
for (int i = 0; i < 10; i++)
{
final ImageButton b = new ImageButton(
new TextureRegionDrawable(new TextureRegion(t)));
b.addListener(new ClickListener()
{
@Override
public void clicked(InputEvent event, float x, float y)
{
if (b.getParent().equals(hGroup))
{
stage.addActor(b);
b.setPosition(
(stage.getWidth() - b.getWidth()) / 2f,
(stage.getHeight() - b.getHeight()) / 2f);
} else
{
hGroup.addActor(b);
}
}
});
hGroup.addActor(b);
}
Gdx.input.setInputProcessor(stage);
}
@Override
public void resize(int width, int height)
{
stage.getViewport().update(width, height);
}
@Override
public void render()
{
Gdx.gl.glClearColor(0f, 0f, 0f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
@Override
public void dispose()
{
stage.dispose();
skin.dispose();
t.dispose();
}
}