代码之家  ›  专栏  ›  技术社区  ›  Franky

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

  •  0
  • Franky  · 技术社区  · 7 年前

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

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

    主要的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()
             }
           }
         }
    

    球qml:

    import QtQuick 2.8
    
    Rectangle {
        width: 20; height: 20
        x: 250; y: 250
        color: "blue"
        radius: width/2
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   folibis    7 年前

    弹跳球的实现非常简单:

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