[SOLVED] Distance between center of the screen and mouse

I have found that the mouse.y is determined from the top of the screen. However, I want to know the distance from the center of the screen to the mouse. Does anyone know the calculation for that?

I think something like this can work:

// given mouse.y is the position from top of the screen
var screenCenterY = this.app.graphicsDevice.height / 2;
var mouseYFromCenter = mouse.y <= screenCenterY ? screenCenterY - mouse.y : mouse.y - screenCenterY;

That seems to work! Thanks!

Do you also know why 360-event.y is NaN?
For example, if event.y is 100 then 360-even.y should be 260?

Yes it should, but debug that event.y property since it seems it’s something else, at some point, than a number. Hence the NaN.

// before doing the subdivision
console.log(event.y);
    var screenCenterY = this.app.graphicsDevice.height / 2;
    var mouseYFromCenter = screenCenterY <= event.y ? event.y - screenCenterY : screenCenterY -event.y;

With this solution, I expect that if I hold my mouse in the center of the screen, mouseYFromCenter is 0, but that’s about 120 now. Any idea what’s still wrong?

I try to use the canvas screen instead of the device screen (so 720/2 = 360), but if i do that the result in the center is still not 0.

So most likely you are testing either on mobile or on a retina/high pixel density display. For that you need to take into account the devicePixelRatio, if you remember you encountered this before as well.

Here is an updated script and example, working both on desktop and mobile:

var MouseCenter = pc.createScript('mouseCenter');

// initialize code called once per entity
MouseCenter.prototype.initialize = function() {
    
    this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this);
    if( this.app.touch ){
        this.app.touch.on(pc.EVENT_TOUCHMOVE, function(event){
            this.onMouseMove(event.touches[0]);
        }, this);        
    }
};

MouseCenter.prototype.onMouseMove = function (event) {
    
    var eventX = event.x * window.devicePixelRatio;
    var screenCenterX = this.app.graphicsDevice.width / 2;
    var mouseXFromCenter = screenCenterX <= eventX ? eventX - screenCenterX : screenCenterX - eventX;        
    
    var eventY = event.y * window.devicePixelRatio;
    var screenCenterY = this.app.graphicsDevice.height / 2;
    var mouseYFromCenter = screenCenterY <= eventY ? eventY - screenCenterY : screenCenterY - eventY;
    
    this.entity.element.text = 'x: ' + mouseXFromCenter.toFixed(0) + '\ny:' + mouseYFromCenter.toFixed(0);
};

https://playcanvas.com/editor/scene/902482

Nice sample scene! And that is working.

I was hoping to solve my other problem this way, but it doesn’t seem to be the case. Maybe you can check that out if you have the time.

https://forum.playcanvas.com/t/distance-between-player-and-mouse

1 Like