QML NumberAnimation.duration行为

问题描述 投票:1回答:1

我正在尝试让玩家在QML中顺利移动到目的地。我正在使用NumberAnimation来动画x,y位置的变化。 NumberAnimation的持续时间应该与玩家必须行进的距离成比例,这样玩家就可以以相同的速度移动,无论他们离目的地有多远。

import QtQuick 1.1

Item {
    width: 720
    height: 720

    MouseArea {
        anchors.fill: parent
        onClicked: {
            var newXDest = mouse.x - player.width / 2;
            var newYDest = mouse.y - player.height / 2;
            var dist = player.distanceFrom(newXDest, newYDest);
            // Make duration proportional to distance.
            player.xMovementDuration = dist; // 1 msec per pixel
            player.yMovementDuration = dist; // 1 msec per pixel
            console.log("dist = " + dist);
            player.xDest = newXDest;
            player.yDest = newYDest;
        }
    }

    Rectangle {
        id: player
        x: xDest
        y: yDest
        width: 32
        height: 32
        color: "blue"
        property int xDest: 0
        property int yDest: 0
        property int xMovementDuration: 0
        property int yMovementDuration: 0

        function distanceFrom(x, y) {
            var xDist = x - player.x;
            var yDist = y - player.y;
            return Math.sqrt(xDist * xDist + yDist * yDist);
        }

        Behavior on x {
            NumberAnimation {
                duration: player.xMovementDuration
//                duration: 1000
            }
        }

        Behavior on y {
            NumberAnimation {
                duration: player.yMovementDuration
//                duration: 1000
            }
        }
    }

    Rectangle {
        x: player.xDest
        y: player.yDest
        width: player.width
        height: player.height
        color: "transparent"
        border.color: "red"
    }
}

通过运行上面的应用程序并执行以下步骤可以证明我的问题:

  1. 单击屏幕右下角。
  2. 立即点击屏幕的中心(或靠近左上角)。

在第二次单击时(当矩形仍在移动时),似乎矩形的数字动画停止(这是我想要的)但它假设目的地的位置(不是我想要的)。相反,我希望动画停止,矩形呈现停止的位置,然后继续到新目的地。

通过将两个NumberAnimation.durations设置为1000,可以看出正确的行为 - 忽略移动速度变得不成比例。

qt animation qml game-physics
1个回答
2
投票

我认为您正在寻找SmoothedAnimation。在动画完成之前,只有两种类型的动画可以很好地处理目标更改。那就是SmoothedAnimation和SpringAnimation。这两个都使用当前位置和速度来确定下一帧中的位置。其他动画类型沿预定曲线移动位置。

只需将NumberAnimation更改为SmoothedAnimation,您的示例对我来说就是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.