简体   繁体   中英

LibGDX Scene2D: Applying Actions to Actors in separate class

I'm having trouble getting a MoveToAction to work on an Actor (menuBackground), when the Actor is in a separate class. I have attached relevant code below- which doesn't make the Actor move at all.

I have had success in apply other actions to the root stage in the MainMenuScreen class, and to a different Actor (Button) in the MainMenuScreen class, but have had no success applying actions to Actors in a separate class.

I've tried putting the MoveToAction in the act(float delta) method within the MenuBackground class, but that didn't work either. Neither did assigning the MoveToAction to the menuBackground from within the MainMenuScreen class.

Note that I am making a call to super.act(delta); within my MenuBackground class.

I would ultimately like to put the code for the MoveToAction within the Actor MenuBackground class, to make things neat and tidy.

Cheers.

Class containing stage:

public class MainMenuScreen implements Screen
{
     private Stage stage;
     public MainMenuScreen()
     {
         stage = new Stage(new FitViewport(800, 480));
         Gdx.input.setInputProcessor(stage);

         menuBackground = new MenuBackground();
         MoveToAction moveToAction = new MoveToAction();
         moveToAction.setPosition(242f, 276f);
         moveToAction.setDuration(10f);
         menuBackground.addAction(moveToAction);
         stage.addActor(menuBackground);

    @Override
    public void render(float delta) 
    {
        Gdx.gl.glClearColor(0, 0, 0, 0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);    
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
...
}

Actor Class:

public class MenuBackground extends Actor
{
    private Texture menuBackgroundTexture;
    private float actorX;
    private float actorY;

    public MenuBackground()
    {
        menuBackgroundTexture = new Texture(Gdx.files.internal("data/menuTitleTexture.png")); 
        actorX = 242f;
        actorY = 350f;
        setBounds(actorX,actorY,316,128);   
    }

    @Override
    public void draw(Batch batch, float alpha)
    {
        batch.draw(menuBackgroundTexture,actorX,actorY);
    }

    @Override    
    public void act(float delta)
    {
        super.act(delta);    
    }
...
}

The problem is inside your draw() method.

Look at code draws your texture, it uses actorX and actorY which are actually fields that don't change their values.

The proper way is:

batch.draw(menuBackgroundTexture, getX(), getY(), getWidth(), getHeight());

So, you should use actor's own fields and getters and don't manage yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM