简体   繁体   中英

Move Actors accuratley LibGDX Scene2d

So i have an actor which is a sprite, set on a screenviewport stage. What i want to do is be able to touch the actor, then touch a spot on the screen it will move that fluently. Currently when i touch the actor it just jumps seemingly to random spots. Here is some of the code in my actor class,

public MyActor(){

    setBounds(sprite.getX(),sprite.getY(),
              sprite.getWidth(),sprite.getHeight());

    setTouchable(Touchable.enabled);

    addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y,
                                 int pointer, int button) {

            MoveByAction mba = new MoveByAction();
            mba.setAmount(x,y);
            MyActor.this.addAction(mba);
            return true;
        }


    });
}

@Override
protected void positionChanged() {
    sprite.setPosition(getX(),getY());
    super.positionChanged();
}

@Override
public void draw(Batch batch, float parentAlpha) {
   sprite.draw(batch);
}
@Override
public void act(float delta){
    super.act(delta);
}

Few things to ask here. First of all, your touch is only on touching your Actor. That's going to be exactly where the actor is. You need to implement at your Scene level some basic state machine to know "on first tap, this actor is selected", then it has to be in a "select where this actor goes" state, and finally when you select a position it has to send that XY to the selected actor to do the move.

Now, as Tenfour04 mentioned, you have to figure out the conversion of the screen's XY of the touch point into the game world's coordinates. Tenfour04 made a good comment about using the projection method on the viewport camera to achieve this. Once you do that, you can send the coordinates to your actor to do the previously mentioned stuff.

To achieve the movement, I'd use the Action framework, like below: actor.addAction(moveTo(x, y, 0.4f, Interpolation.circle));

This page shows you all the nice actions available for Scene2d: https://github.com/libgdx/libgdx/wiki/Scene2d#actions

Hope that's what you needed. :)

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