Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Window {
- id: w
- visible: true
- width: 360
- height: 360
- property var objects: []
- Rectangle {
- width: 20
- height: 20
- color: "red"
- x: 100
- y: 100
- radius: 20
- property double dx: 0
- property double dy: 0
- property double g: 9.8
- property double k: 20
- Component.onCompleted: {
- objects.push(this)
- }
- }
- property int fps: 50
- property double skipTicks: 1000 / fps
- property real nextTick: (new Date).getTime()
- property real maxFrameSkip: 5
- Timer {
- running: true
- repeat: true
- interval: 10
- onTriggered: {
- var loops = 0
- while ((new Date).getTime() > nextTick && loops < maxFrameSkip) {
- gUpdate()
- nextTick += skipTicks
- loops++
- }
- var interpolation = ((new Date).getTime() + skipTicks - nextTick)/skipTicks
- gRender(interpolation)
- }
- }
- function gUpdate() {
- objects.forEach(function(o) {
- var vertical = false
- var horizontal = false
- var isLeft = false
- var isTop = false
- o.dy += o.g/o.k
- o.dx += 0.001 * (o.dx > 0 ? -1 : 1)
- // это условие должно было остановить дрожание
- // оно работает если убрать этот треклятый while() из таймера
- // if(o.y >= w.height - o.height - 1
- if(o.y + o.dy >= w.height - o.height - 1
- && Math.abs(o.dy) < 0.1) {
- o.dx = 0
- o.dy = 0
- }
- // узнаем об какую границу окна ударился шарик
- // и в какую сторону он движется
- if(o.x + o.dx <= 0) {
- horizontal = true
- isLeft = true
- }
- else if(o.x + o.dx + o.width >= w.width) {
- horizontal = true
- }
- if(o.y + o.dy <= 0) {
- vertical = true
- isTop = true
- }
- else if(o.y + o.dy + o.height >= w.height) {
- vertical = true
- }
- if (horizontal && vertical) {
- if (o.width > o.height) {
- horizontal = false
- } else {
- vertical = false
- }
- }
- // если шарик ударился, то инвертируем скорость
- // и уменьшаем ее на коэфф.
- if (horizontal) {
- o.dx *= -1
- o.dx += o.k/o.g * (o.dx > 0 ? -1 : 1)
- if (isLeft) {
- o.x = 0
- } else {
- o.x = w.width - o.width
- }
- }
- else if (vertical) {
- o.dy *= -1
- o.dy += o.k/o.g
- if (isTop) {
- o.y = 0
- } else {
- o.y = w.height - o.height
- }
- }
- })
- }
- function gRender(interpolation) {
- objects.forEach(function(o) {
- o.x += o.dx * interpolation
- o.y += o.dy * interpolation
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment