[SOLVED] Problem with using Device Pixel Ratio

I’m trying to make a target indicator. For this I use this.app.graphicsDevice. This works fine on my laptop and mobile until I check the Device Pixel Ratio option. Then there is a big offset on my mobile. Is there an alternative for using this.app.graphicsDevice to avoid this problem?

Hi @Albertos,

When you say you use this.app.graphicsDevice, you mean how? To get the width and the height of the canvas?

You may need to take into consideration on your coordinate calc the device pixel ratio of the device:

// width in physics pixels, when having device pixel ratio on
var width = this.app.graphicsDevice.canvas.width * this.app.graphicsDevice.maxPixelRatio;

Thanks for your reaction @Leonidas! First I try to implant your solution in the script below. This script has to set a 2D element (with the script) on the same position as a 3D entity. If I change in the last line device.height for your deviceHeight, it works the same on my laptop, but still a wrong result on my mobile.

// update code called every frame
EntityIcon.prototype.update = function(dt) {
    // world space position of target
    var worldPos = this.target.getPosition();
    var screenPos = new pc.Vec3();
    // get screen space co-ord
    this.camera.camera.worldToScreen(worldPos, screenPos);
    // convert to screen component co-ordinates
    var screenEntity = this.entity.element.screen;
    var scale = screenEntity.screen.scale;
    var device = this.app.graphicsDevice.canvas;
    var deviceHeight = this.app.graphicsDevice.canvas.height * this.app.graphicsDevice.maxPixelRatio;
    var deviceWidth = this.app.graphicsDevice.canvas.width * this.app.graphicsDevice.maxPixelRatio;
    // this is not working on mobile when Device Pixel Ratio is enabled
    this.entity.setLocalPosition(screenPos.x / scale, (device.height - screenPos.y) / scale, 0); 

What are you trying to do from a high level perspective?

I’m trying to make an element follow an entity until the entity leaves the screen. When the entity has left the screen, the element will only follow the entity to a limited extent so that the element remains visible on the edge of the screen.

@Albertos, hmm, shouldn’t this one work?:

1 Like

Perfect @LeXXik! Now my basic target indicator works well on both devices with Device Pixel Ratio enabled. I will show the result in the other topic when I am completely done.