[SOLVED] Is there a way to detect a mobile device?

Basically, I want to add some touch controls to my games, but hide the interface for touch when someone is using a web browser (since they can just use assigned keys).

SO the way I would imagine the code would work would be like “Is player on mobile? if so show touch control interface”

Otherwise, it’s hidden and unusable on the web browser.

An example of this would be basically putting the arrow keys on the window for mobile users to replace the inputs that would be found on a keyboard/controller.

Here is are some visual examples.

With entity picking, I can use those scripts to easily make these controls work with touch or mouse. Just need to know if there is a way for the game to know that a user is on a phone/tablet or not so that way i can build simple code to hide/show the relevant interface.

Generally in the web, trying to divide by platform - will lead to problems, as there are “hybrid” platforms, or simply no guaranteed way to be correct, leading to many edge cases.

Best way to do is to simply check if certain feature is supported.
If touch is supported, show touch UI. If touch is not supported, simply don’t show touch UI.
Do remember there are devices with touch and keyboard, such as many modern laptops with touch screens. In such case, show touch as before, but if user start to use keyboard, hide touch. This is of course case specific, and if you can’t imagine possibility of user using both at same time, then it is enough to do what described above.

Something like???

 if (touch) {
       showUI = true;
    }
if (this.app.touch) {
    // Touch is supported
}

Another nice touch you can do if a device has both touch and keyboard support is to hide the touch controls if the keyboard starts to be used.

Yea haha didn’t put the whole syntax in but that’s what i meant :wink:

So within that code I could do

if(this.app.touch) {
  showUI = true;
} else if(keyboardInputs){
  showUI = false;
}

Also, I posted in the CODING thread about selecting between different entities. Would love to know your thoughts on that?

Here’s a link to that thread.

AFAIK, with PlayCanvas there is always keyboard support regardless if a keyboard is actually attached.

You can just do this TBH

// Same as showTouchUi = this.app.touch != null && this.app.touch != undefined
showTouchUi = !!this.app.touch;

If somebody is still looking for a solution: You can check against platforms now:

https://developer.playcanvas.com/en/api/pc.platform.html

Have a nice day

2 Likes