Best way to use custom controls

Before ES times i always uesd controls to influence the spatial and sub spacials only.

A common example:

You have turrets that can track units.

The control would be something like:

if target not null
  rotate turret to face player
else 
  rotate to idle

And setting the target to the control is done in an appstate that has access to all spatials

In the above example you have Application already in your control. From there you can access the inputManager with getInputManager():

    public class MyControl extends AbstractControl {

        private Application app;
        private boolean doRotate = false;

        public MyControl(Application app) { // or subclasses of your my app
            this.app = app;
        }

        @Override
        public void setSpatial(Spatial spatial) {
            if(spatial != null) {
                // This is kinda your init method because if you attach a control to a spatial this gets called
                app.getInputManager().addMapping("ROTATE", new KeyTrigger(KeyInput.KEY_R));
                app.getInputManager().addListener((ActionListener)(name, isPressed, tpf) -> {
                    // Your logic goes here
                    doRotate = isPressed;
                }, "ROTATE");
            } else {
                // And this is your dispose method because if the spatial is null the controls is being detached
                app.getInputManager().deleteMapping("ROTATE");
                app.getInputManager().deleteTrigger("ROTATE", new KeyTrigger(KeyInput.KEY_R));
            }
        }

        @Override
        protected void controlUpdate(float tpf) {
            if(doRotate) {
                spatial.rotate(0f, FastMath.PI * tpf, 0f);
            }
        }

        @Override
        protected void controlRender(RenderManager rm, ViewPort vp) {
        }
    }

    // And use it like this somewhere else in your code...
    Node node = new Node("your character");
    node.addControl(new MyControl(yourApplicationInstance));



I was so sleepy in the morning, I didn’t realize it’s a 11 year old thread lmao :laughing:

1 Like