Device Pixel Ratio Causing issues in drag on mobile

Hey guys,

I am trying to drag a image using the mouse, but facing a issue on mobile. The script works perfectly on desktop/pc even with device pixel option enabled, but when I try it out on my mobile, it doesnt work, and if I disable the device pixel ratio then it starts working on mobile.

Any help regarding this would be highly appreciated:

Here is the build:

Here is the project:
https://playcanvas.com/editor/scene/956910

Regards

Hi @WebGl_Force and welcome,

Your code is correct, you just need to take into account the device pixel ratio in your drag calculation. Something like this:

var screenX = (this.axis == 'x' || this.axis == 'xy') ? (this.mousePos.x-xOffs)*scale : this.anchorPos.x ;
var screenY = (this.axis == 'y' || this.axis == 'xy') ? (-this.mousePos.y+yOffs)*scale  : this.anchorPos.y ;

    // Take into account pixel ratio
    var pixelRatio = this.app.graphicsDevice.maxPixelRatio;
    screenX *= pixelRatio;
    screenY *= pixelRatio;

this.handle.setLocalPosition(screenX,screenY,0);

Hey @Leonidas

Thanks for the welcome.

I have taken the pixelRatio, as you mentioned above. On pc it gives value of 1 so the drag works fine on my PC, but on my mobile it is giving a value of 3, which when I multiply, just shoots the image out of the screen, I am not sure how to take this pixel ratio in account.

I have updated the code as you mentioned on my project,
https://playcanvas.com/editor/scene/956910

Basically the idea is on mobile the reported canvas width/height and the scale of the screen are affected by the device pixel ratio.

So you need to normalize those values before calculating your input. For your project something like this will work:

UISlider.prototype.updateDrag = function() {

    if( ! this.isDragging ) return ;    

    var device = this.app.graphicsDevice;
    var pixelRatio = this.app.graphicsDevice.maxPixelRatio;
    
    var xOffs = this.handle.element.anchor.x*device.width / pixelRatio;
    var yOffs = this.handle.element.anchor.y*device.height / pixelRatio;
    var scale = 1/this.screen.scale * pixelRatio;


    var screenX = (this.axis == 'x' || this.axis == 'xy') ? (this.mousePos.x-xOffs)*scale : this.anchorPos.x ;
    var screenY = (this.axis == 'y' || this.axis == 'xy') ? (-this.mousePos.y+yOffs)*scale  : this.anchorPos.y ;

    this.handle.setLocalPosition(screenX,screenY,0);
};
2 Likes

Oh I see what I was doing wrong,

Thank you Leonidas, really appreciate the help!

1 Like