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



我在QML项目中的矩形内有一个动画的球,并希望当它撞到矩形的边界时,它会返回到内部,直到它撞到另一个边框,然后它再次支持,又一个。

我已经为此编写了此代码,但是不知道使用什么代码在撞到边界时会返回!
你能帮我吗?

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
}

弹跳球的非常简单的实现:

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);
            }
        }
    }
}

最新更新