How to achieve velocity of a moving component
Below is a simplified version of a bigger QML program where a waiting loop (while) in a function is used to measure the time of an event (collision).
Everything in the code looks fine to me, and we expect when the collision occurs, the while loop terminates by the function's return statement, but in reality it crashes, I don't know why! :(
Code:
import QtQuick 2.12
import QtQuick.Window 2.12
Window {
id: window
visible: true
width: 1000; height: 800
color: "royalblue"
property real colTime_1: new Date().getTime()
property real colTime_2
property real speed
Rectangle {
id: ball
x: window.x + 50; y: window.y + 50
width: 18; height: 18
color: "white"
radius: width/2
}
// Move the ball
onFrameSwapped: {
ball.x += 5
ball.y += 3
}
Component.onCompleted: {
if (catchColTime()) console.log("Speed = ", speed)
}
function catchColTime() {
while(true)
if (ball.x >= window.width) {
colTime_2 = new Date().getTime()
speed = window.width / (colTime_2 - colTime_1)
return true
}
}
}
Re: How to achieve velocity of a moving component
Hi, you should check with a debugger when and where the crash happens.
For example this line
Quote:
speed = window.width / (colTime_2 - colTime_1)
might cause a crash if colTime_2 and colTime_1 are the same (division by zero).
Ginsengelf