目标:在屏幕中央旋转图像,移动等于左或右touchDragged事件。
现在我创建了一个基本舞台,并将舞台(centerMass.png)添加到舞台上。它是这样创建和渲染的:
public class Application extends ApplicationAdapter {
Stage stageGamePlay;
@Override
public void create () {
//setup game stage variables
stageGamePlay = new Stage(new ScreenViewport());
stageGamePlay.addActor(new CenterMass(new Texture(Gdx.files.internal("centerMass.png"))));
Gdx.input.setInputProcessor(stageGamePlay);
}
@Override
public void render () {
Gdx.gl.glClearColor(255f/255, 249f/255, 236f/255, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//before drawing, updating actions that have changed
stageGamePlay.act(Gdx.graphics.getDeltaTime());
stageGamePlay.draw();
}
}
然后我有一个单独的类文件,其中包含CenterMass类,扩展了Image。我很熟悉我可以扩展Actor,但我不确定使用Actor vs Image会获得什么好处。
在CenterMass类中,我创建纹理,设置边界,设置可触摸并将其居中在屏幕上。
在CenterMass类中,我还有一个InputListener监听事件。我有一个touchDragged的覆盖设置,我试图获取拖动的X和Y,并使用它来相应地设置旋转动作。该课程如下:
//extend Image vs Actor classes
public class CenterMass extends Image {
public CenterMass(Texture centerMassSprite) {
//let parent be aware
super(centerMassSprite);
setBounds(getX(), getY(), getWidth(), getHeight());
setTouchable(Touchable.enabled);
setPosition(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
setRotation(90f);
addListener(new InputListener(){
private int dragX, dragY;
private float duration;
private float rotateBy = 30f;
@Override
public void touchDragged(InputEvent event, float x, float y, int pointer) {
//get
float dX = (float)(x-dragX)/(float)Gdx.graphics.getWidth();
float dY = (float)(dragY-y)/(float)Gdx.graphics.getHeight();
duration = 1.0f; // 1 second
Actions.sequence(
Actions.parallel(
Actions.rotateBy(rotateBy, duration),
Actions.moveBy( dX, dY, duration)
)
);
}
});
}
@Override
protected void positionChanged() {
//super.positionChanged();
}
@Override
public void draw(Batch batch, float parentAlpha) {
//draw needs to be available for changing color and rotation, I think
batch.setColor(this.getColor());
//cast back to texture because we use Image vs Actor and want to rotate and change color safely
((TextureRegionDrawable)getDrawable()).draw(batch, getX(), getY(),
getOriginX(), getOriginY(),
getWidth(), getHeight(),
getScaleX(), getScaleY(),
getRotation());
}
@Override
public void act(float delta) {
super.act(delta);
}
}
问题: 我无法按照我想要的方式旋转它。我已经能够以不可预测的方式转变它。任何指导都将非常感谢。
答案 0 :(得分:0)
从你的代码来看似乎一切都很好。除了你没有设置图像的任何原点。没有设置原点它默认设置为0,0。(图像的左下角) 因此,如果您想要将原点的图像旋转到中心,则必须将原点设置为imageWidth / 2。 imageHeight / 2。
setOrigin(imageWidth/2,imageHeight/2)// something like this