一个在矩形内旋转的球,一个QML项目

时间:2017-12-10 07:51:49

标签: animation qml qtquick2 qtquickcontrols2

我在QML项目的矩形内部有一个球动画,如下所示,当它碰到Rectangle的边框时,它会返回到内部直到它碰到另一个边界,然后再次返回,依此类推。

我为此编写了这段代码,但是不知道使用什么代码让球在击中边界时返回!
你能帮帮我吗?

main.qml:

import QtQuick 2.6
import QtQuick.Window 2.2

 Window {
    visible: true
    width: 800
    height: 600
    title: qsTr("Ball_in_Room")

    Rectangle {
        id: root
        width: 700; height: 500
        border.width: 10
        border.color: "gray"
        color: "moccasin"
        property real xPos: root.width
        property real yPos: Math.random() * root.height

        Ball { id: ball }

        ParallelAnimation {
           id: anim
               NumberAnimation {
                        target: ball
                        properties: "x"
                        to: root.xPos
                        duration: 1000
                        easing.type: Easing.Linear
                    }
               NumberAnimation {
                        target: ball
                        properties: "y"
                        to: root.yPos
                        duration: 1000
                        easing.type: Easing.Linear
                    }
        }

         MouseArea {
             anchors.fill: ball
             onClicked: anim.start()
         }
       }
     }

Ball.qml:

import QtQuick 2.8

Rectangle {
    width: 20; height: 20
    x: 250; y: 250
    color: "blue"
    radius: width/2
}

1 个答案:

答案 0 :(得分:1)

非常简单的弹跳球实现:

Rectangle {
    id: container
    anchors.fill: parent
    border.color: "orange"
    border.width: 3

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

        Timer {
            interval: 1
            repeat: true
            running: true
            onTriggered: {
                ball.x = ball.x + (ball.xincrement * 2.0);
                ball.y = ball.y + (ball.yincrement * 2.0);
                if(ball.x <= 0 || ball.x + ball.width >= container.width)
                    ball.xincrement *= (-1);
                if(ball.y <= 0 || ball.y + ball.height >= container.height)
                    ball.yincrement *= (-1);
            }
        }

    }
}