Virtual keyboard

Hello!
I have a virtual keyboard in my game that looks something like this:

Each button is a prefab. My question is what is the best way to listen for button events. I just don’t want to assign events to all buttons every time. I don’t know exactly what the best approach to this problem is.
But in the end I’d like to have something similar to:

this.keyboardNode.on(‘input’, (key) => {
// Do something
});

Does anyone have any ideas on how best to implement this?

I use Cocos creator 3.8.1.

There is no other way than binding the touch event to every button.
But you can do it quickly by looping through children of the buttons’ parent node. Something like

ParentNode.children.map((button)=>{
       button.on('touchend', ()=>{
               const labelComp = cc.find('label', button).getComponent(cc.Label);
               console.log(labelComp.string);
       });
})

The event name “touchend” is just example, pls replace it by correct event name for 3.8.1
And cc.find() should be only “find”

1 Like
@ccclass('VirtualKeyboard')
export class VirtualKeyboard extends Component {
    start() {
        this.node.on(Input.EventType.TOUCH_START, (e: EventTouch)=>{
            let touchPos = e.getUILocation();
            let keyNodes = this.node.children;
            for(let key of keyNodes){
                let isHit = key.getComponent(UITransform).getBoundingBoxToWorld().contains(touchPos);
                if(isHit){
                    console.log("Touch Key: " + key.name);
                    break;
                }
            }
        }, this);
    }
}

1 Like

For some reason it doesn’t work. I tried to use your example with the same node structure as yours.
I use Cocos Creator 3.8.1 (Maybe this is the reason?)
noname

Remove button’s Button component. Button component will swallow the touch event.

1 Like