QML组件碰撞测试方法

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

好吧,可能有许多QML程序,如果两个组件相互冲突,程序员就会根据它定义一个动作。在如下所示的程序中,我们希望专注于该碰撞并尝试知道如何定义一个函数,告诉我们是否完成了这样的碰撞。

下面的代码是更大程序的一部分。我试着在代码中使用一个名为collision的函数。到目前为止的问题是它运作不佳。我想知道QML中是否有内置函数“或”,如果有一个很好的代码用于此目的。

球拍有三个可能与球碰撞的面:前面是长球,上面是下球。特别的问题是当球从上面或下面碰撞时,球会进入球拍内部! 我想解决的问题是。我希望当球从任何面孔击中球拍时,它会反射出来。

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 720
    height: 620
    title: qsTr("Collision 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: 50

    MouseArea {
        anchors.fill: parent
        drag.target: root
        drag.axis: Drag.YAxis
        drag.minimumY: table.y
        drag.maximumY: table.y + table.height - 50
    }
}
qt qml collision-detection collision qqmlapplicationengine
1个回答
1
投票

对于简单检查,无论一个点是否在Item内,您都可以使用contains(point p)

这个函数需要一个局部坐标点(相对于Items原点),所以你应该使用mapFromItem(...)mapToItem(...)来获得正确的位置。

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