移动小部件时的QML性能问题会影响彼此的移动

时间:2018-01-03 19:15:45

标签: android qt qml qt-quick qqmlcomponent

以下是显示问题的代码的最小版本:

桌面套件上播放游戏时移动球拍(Windows)不会影响球的移动速度,但在运行时一个Android设备,移动球拍影响球的运动速度,好像他们的动作已经绑在一起。
请问有什么解决方案吗?

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 720
    height: 620
    title: qsTr("Movement Test")

    Rectangle {
        id: table
        anchors.fill: parent
        color: "gray"

        Rectangle {
            id: ball
            property double xincrement: Math.random() + 0.5
            property double yincrement: Math.random() + 0.5
            width: 15
            height: width
            radius: width / 2
            color: "white"
            x: 300; y: 300
        }

        Racket {
            id: myRacket
            x: table.width - 50
            y: table.height/3
            color: "blue"
        }

        Timer {
            interval: 5; repeat: true; running: true

            function collision() {
                if((ball.x + ball.width >= myRacket.x  &&
                    ball.x < myRacket.x + myRacket.width) &&
                   (ball.y + ball.height >= myRacket.y &&
                    ball.y <= myRacket.y + myRacket.height))
                    return true
                return false
            }

            onTriggered: {
                if(ball.x + ball.width >= table.width)
                    running = false

                else if(ball.x <= 0)
                    ball.xincrement *= -1

                else if (collision())
                    ball.xincrement *= -1

                ball.x = ball.x + (ball.xincrement * 1.5);
                ball.y = ball.y + (ball.yincrement * 1.5);

                if(ball.y <= 0 || ball.y + ball.height >= table.height)
                    ball.yincrement *= -1
            }
        }
    }
}

Racket.qml

import QtQuick 2.9

Rectangle {
    id: root
    width: 15; height: 65
    property int oldY: y
    property bool yUwards: false
    property bool yDwards: false

    onYChanged: {
        if(y > oldY)  yDwards = true
        else if (y < oldY)  yUwards = true
        oldY = y
    }

    MouseArea {
        anchors.fill: parent
        anchors.margins: -root.height
        drag.target: root
        focus: true
        hoverEnabled: true
        pressAndHoldInterval: 0
        drag.axis: Drag.YAxis
        drag.minimumY: table.y
        drag.maximumY: table.height - root.height - 10
    }
}

1 个答案:

答案 0 :(得分:0)

Qt尝试渲染每个~16-17ms。如果将计时器设置为5毫秒,它将尝试每帧触发3到4次。

其他正在发生的事情可能会妨碍它保持这种速度。如果设备功能较弱,则此效果可能比其他设备更明显。

要查看Timer是否达到设定费率,您可以打印当前ms部分时间:

console.log(Qt.formatTime(new Date(), "zzz"))

如果Timer达到全速,则记录的值应为5 appart。如果它没有,它将与5不同。

最简单的方法是设置球将移动到的目标位置,并为该移动设置动画(使用Animation - 类型)。 Animation应注意保持移动速度,即使在帧速率可能下降的情况下也是如此。

如果你想手动完成,而不是使用计时器,你应该使用onAfterRendering - 插槽(我想到Window)。当某些东西在屏幕上移动并触发渲染时,将触发此操作。这也是检查碰撞的理想时刻。

然后,您需要计算新的位置,包括其速度,当前位置和经过的时间。后来你可以从JS Date() - 对象获得,或者使用QElapsedTimer

以某种方式从C ++中公开它