[SOLVED] Mobile Raycast is not precise on vertical screen

Hi guys,
I’m handling mobile raycast like this, but for some reasons when i flip the screen vertically it is a lot less precise than horizontal.

Selection.prototype.touchStart = function (e) {
    // Only perform the raycast if there is one finger on the screen
    if (e.touches.length === 1) {
        this.doRaycast(e.touches[0]);
    }
    e.event.preventDefault();
};

Selection.prototype.doRaycast = function (screenPosition) {
    // Calculate the screen position in camera viewport space 
    var camera = this.entity.camera;
    var rect = camera.rect;
    var screenWidth = this.app.graphicsDevice.width / this.app.graphicsDevice.maxPixelRatio;
    var screenHeight = this.app.graphicsDevice.height / this.app.graphicsDevice.maxPixelRatio;

    // Work out the normalised screen positions we are clicking 
    var nx = ((screenPosition.x / screenWidth) - rect.x) / rect.z;

    // Y is inverted in screen coords so we want to use the reminder of the rect
    var ny = ((screenPosition.y / screenHeight) - (1 - rect.y - rect.w)) / rect.w;

    // Are we clicking in our viewport?
    if (nx >= 0 && nx < 1 && ny >= 0 && ny < 1) {
        // Convert back to screen coordinates for screen to world
        var mx = nx * screenWidth;
        var my = ny * screenHeight;

        // The pc.Vec3 to raycast from
        var from = this.entity.camera.screenToWorld(mx, my, this.entity.camera.nearClip);

        // The pc.Vec3 to raycast to 
        var to = this.entity.camera.screenToWorld(mx, my, this.entity.camera.farClip);

        // Raycast between the two points
        var result = this.app.systems.rigidbody.raycastFirst(from, to);
        
        if (result) {
            var hitEntity = result.entity;
            hitEntity.destroy();
        }    
    }
};

Hi @SaccoVinc and welcome,

It should be the same if your coordinates and width/height used are always the correct ones. I’d start by debugging those values, check using the console or the debugger if the reported values make sense or something in there is inverted.

Hi, @Leonidas thanks for your response, i fixed It, I was using 2 cameras in my project and the camera that was handling the script was child of the other one.
I Just separated them and It worked.

Also apologize for any english mistake, Sorry.

1 Like

Nice, no worries about the language, marking this as solved!