Search code examples
javalibgdxtouchpad

Libgdx: How do you separate the controls from the movable object?


I'm very new to Libgdx. I have looked through many helpful tutorials, but nothing has implemented the following structure. I've implemented a movable object that is an extension of InputAdapter, and overrides keyDown/Up to update its(object) location. Now, I've implemented a touchPadController class that has a touchpad and knob that are visible on the screen. Then, I added a variable that is an object of the touchPadController class.

My ultimate goal in the future is to completely separate the controls class from any movable objects/characters.

The problem: I want to call the setInputProcessor only to the movable objects/characters, and not directly to the touchPadController class. I want the parent movable object to call its own controls. But, I do not know where the of call for the touchPadController functions would happen??

  • I tried this but it didn't work:

    //movable object @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { Gdx.input.setInputProcessor(touchPadController); } //touchPadController @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { parent.newSpeedX = touchpad.getKnobPercentX() * Speed; parent.newSpeedY = touchpad.getKnobPercentY() * Speed; return true; }

*Where should I call to the touchPadController within the parent(movable object)?


Solution

  • Separate your controllers and your characters/entities like this:

    public class Controller extends InputAdapter {
        private Entity _controllee;
    
        public void setControllee(Entity toControl) {
            _controllee = toControl;
        }
    
        // Override whichever InputAdapter methods you need to control your moveable objects, e.g.:
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            _controllee.newSpeedX = touchpad.getKnobPercentX() * Speed;
            _controllee.newSpeedY = touchpad.getKnobPercentY() * Speed;
            return true;
        }
    }
    

    And finally somewhere in your ApplicationListener or Screen you create an instance of the controller, attach a controllee to it via setControlle and set it as an input processor, like this:

    Controller myController = new Controller();
    myController.setControllee(/*one of your movable objects*/);
    Gdx.input.setInputProcessor(myController);