ElementDragHelper _calculateDragScale error in code

I’m utilizing the ElementDragHelper to enable drag functionality for a menu, which functions well. However, there’s an issue with the calculateDragScale function, as it modifies the current variable before verifying it, leading to an error.

_calculateDragScale() {
        let current = this._element.entity.parent;
        const screen = this._element.screen && this._element.screen.screen;
        const isWithin2DScreen = screen && screen.screenSpace;
        const screenScale = isWithin2DScreen ? screen.scale : 1;
        const dragScale = this._dragScale;

        dragScale.set(screenScale, screenScale, screenScale);

        while (current) {
            dragScale.mul(current.getLocalScale());
            current = current.parent; // this should be moved to after the if statement

            if (isWithin2DScreen && current.screen) {
                break;
            }
        }

        dragScale.x = 1 / dragScale.x;
        dragScale.y = 1 / dragScale.y;
        dragScale.z = 0;
    }

For anyone curious as how to solve the issue just extend pc.ElementDragHelper and create a custom class then replace the _calculateDragScale with the below code it will then work in a 2D screen without having to add another screen.

_calculateDragScale() {
        const dragScale = this._dragScale.clone();
        const screen = this._element.screen && this._element.screen.screen;
        const isWithin2DScreen = screen && screen.screenSpace;
        const screenScale = isWithin2DScreen ? screen.scale : 1;

        dragScale.set(screenScale, screenScale, screenScale);

        let current = this._element.entity.parent as pc.Entity;

        while (current) {
            dragScale.mul(current.getLocalScale());

            if (isWithin2DScreen && current.screen) {
                break;
            }

            current = current.parent as pc.Entity;
        }

        dragScale.x = 1 / dragScale.x;
        dragScale.y = 1 / dragScale.y;
        dragScale.z = 0;

        this._dragScale.copy(dragScale); // Update the original _dragScale
    }
1 Like

Thank you for sharing!

If you believe there is a bug in the ElementDragHelper, please create a new issue in the engine repo, so it can be fixed:

I believe you ran into this issue before Draggable element causing error when under root 2D Screen · Issue #2613 · playcanvas/engine · GitHub

Should i create another issue?

To solve just move the current variable after the if statement.

current = current.parent as pc.Entity;
2 Likes

Ah, I remember now. Thanks! No need to create a new one :slight_smile: