避免碰撞的QGraphicsItem形状动鼠

0

的问题

一个有趣的讨论提出了 在这里 关于防止碰撞的圈子,由QGraphicsEllipseItems,在QGraphicsScene. 该问题缩小了范围,到2碰撞的项目,但更大的目标仍然存在, 那么对于任何数量的碰撞?

这是期望的行为:

  • 当一个项目被拖动过其他项目,他们不应该重叠,相反,它应该移动的那些项目尽可能接近老鼠。
  • 它不应该"瞬间移动",如果它得到被阻止在通过其他项目。
  • 它应该是平稳和可预测的运动。

因为这变得越来越复杂,要找到最好的"安全"位置的圈子,而它的移动,我想提出另一种方式来实现这一使用一个物理模拟器。

collision pymunk pyqt5 python
2021-11-23 02:01:24
1

最好的答案

3

鉴于所述的行为以上这是一个很好的候选人2D刚体物理,也许可以做不但是,这将是难以得到它的完美。 我使用 pymunk 在这个例子因为我熟悉它,但是同样的概念将与其他图书馆。

现场有一个运动身来表示鼠和界的代表是静态的机构。 虽然一个圆圈是选择就切换到一个动态的主体和受到约束的小鼠通过一个阻尼泉。 其位置的是最新的空间是由一个定时步骤,在每个超时间间隔。

该项目是不实际上移动的方式相同 ItemIsMovable 旗未启用的,这意味着它不再移动立即用鼠标。 这是非常接近,但有一个小的延迟,尽管你可能更喜欢这个更好看看它是如何反应的冲突。 (即使这样,你可以调整参数,把它移动的速度/接近鼠比我**).

另一方面,冲突是完全处理,并将支持其他种类的形状。

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import pymunk

class Circle(QGraphicsEllipseItem):

    def __init__(self, r, **kwargs):
        super().__init__(-r, -r, r * 2, r * 2, **kwargs)
        self.setFlag(QGraphicsItem.ItemIsSelectable)
        self.static = pymunk.Body(body_type=pymunk.Body.STATIC)
        self.circle = pymunk.Circle(self.static, r)
        self.circle.friction = 0
        mass = 10
        self.dynamic = pymunk.Body(mass, pymunk.moment_for_circle(mass, 0, r))
        self.updatePos = lambda: self.setPos(*self.dynamic.position, dset=False)

    def setPos(self, *pos, dset=True):
        super().setPos(*pos)
        if len(pos) == 1:
            pos = pos[0].x(), pos[0].y()
        self.static.position = pos
        if dset:
            self.dynamic.position = pos

    def itemChange(self, change, value):
        if change == QGraphicsItem.ItemSelectedChange:
            space = self.circle.space
            space.remove(self.circle.body, self.circle)
            self.circle.body = self.dynamic if value else self.static
            space.add(self.circle.body, self.circle)
        return super().itemChange(change, value)

    def paint(self, painter, option, widget):
        option.state &= ~QStyle.State_Selected
        super().paint(painter, option, widget)


class Scene(QGraphicsScene):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.space = pymunk.Space()
        self.space.damping = 0.02
        self.body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
        self.space.add(self.body)
        self.timer = QTimer(self, timerType=Qt.PreciseTimer, timeout=self.step)
        self.selectionChanged.connect(self.setConstraint)

    def setConstraint(self):
        selected = self.selectedItems()
        if selected:
            shape = selected[0].circle
            if not shape.body.constraints:
                self.space.remove(*self.space.constraints)
                spring = pymunk.DampedSpring(
                    self.body, shape.body, (0, 0), (0, 0),
                    rest_length=0, stiffness=100, damping=10)
                spring.collide_bodies = False
                self.space.add(spring)

    def step(self):
        for i in range(10):
            self.space.step(1 / 30)
        self.selectedItems()[0].updatePos()

    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        if self.selectedItems():
            self.body.position = event.scenePos().x(), event.scenePos().y()
            self.timer.start(1000 / 30)
            
    def mouseMoveEvent(self, event):            
        super().mouseMoveEvent(event)
        if self.selectedItems():
            self.body.position = event.scenePos().x(), event.scenePos().y()
        
    def mouseReleaseEvent(self, event):
        super().mouseReleaseEvent(event)
        self.timer.stop()

    def addCircle(self, x, y, radius):
        item = Circle(radius)
        item.setPos(x, y)
        self.addItem(item)
        self.space.add(item.circle.body, item.circle)
        return item


if __name__ == '__main__':
    app = QApplication(sys.argv)
    scene = Scene(0, 0, 1000, 800)
    for i in range(7, 13):
        item = scene.addCircle(150 * (i - 6), 400, i * 5)
        item.setBrush(Qt.GlobalColor(i))    
    view = QGraphicsView(scene, renderHints=QPainter.Antialiasing)
    view.show()
    sys.exit(app.exec_())

**可以调整如下:

  • 弹簧 stiffnessdamping
  • 身体 massmoment 惯性
  • 空间 damping
  • Space.step 时间步长/多少电话每QTimer超时
  • QTimer interval
2021-12-01 01:57:12

这是完美的!
drivereye

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................