kivy,检查旋转后两个小部件是否重叠

时间:2014-12-08 22:52:01

标签: python kivy

使用kivy,我怎样才能检查一个小部件在旋转后是否与另一个小部件重叠。使用collide_widget方法不考虑轮换,因此下面的代码片段打印出来"正在碰撞"即使你可以看到矩形没有重叠。还有其他聪明的东西可以用kivy做,这样可以让我在旋转后检查与矩形的碰撞吗?

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics.context_instructions import PopMatrix, PushMatrix
from kivy.graphics import Rectangle, Rotate

class RotatableRect(Widget):
    def __init__(self, angle=0, **kwargs):
        super(RotatableRect, self).__init__(**kwargs)

        with self.canvas.before:
            PushMatrix()
            self.rot = Rotate()
            self.rot.angle = angle
            self.rot.origin = self.center
            self.rot.axis = (0, 0, 1)
            self.rect = Rectangle(pos=self.pos, size=self.size)

        with self.canvas.after:
            PopMatrix()


class MainWidget(Widget):
    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)

        self.rect1 = RotatableRect(pos=[10, 100], size=[100, 50])
        self.rect2 = RotatableRect(pos=[100, 50], size=[100, 50], angle=45)
        self.add_widget(self.rect1)
        self.add_widget(self.rect2)

        if self.rect1.collide_widget(self.rect2):
            print 'is colliding'

class TheApp(App):
    def build(self):
        parent = Widget()
        parent.add_widget(MainWidget())
        return parent

if __name__ == '__main__':
    TheApp().run()

1 个答案:

答案 0 :(得分:1)

检查Rotabox中的kivy-garden窗口小部件 我最初是为了这个精确的碰撞+旋转目的而制造的,尽管从那时起它经历了很多变化。

首先,在项目中加入rotabox.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Rectangle
from rotabox import Rotabox


class RotatableRect(Rotabox):
    def __init__(self, **kwargs):
        super(RotatableRect, self).__init__(**kwargs)
        with self.canvas:
            self.rect = Rectangle(pos=self.pos, size=self.size)


class MainWidget(Widget):
    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)    
        self.rect1 = RotatableRect(pos=[10, 100], size=[100, 50])
        self.rect2 = RotatableRect(pos=[100, 50], size=[100, 50], angle=45)
        self.add_widget(self.rect1)
        self.add_widget(self.rect2)

        # for a stationary rotabox, it's essential to wait for it to setup, 
        # before any collision checks
        self.rect1.bind(ready=self.check)

    def check(self, *args):
        if self.rect1.collide_widget(self.rect2):
            print '  is colliding'    

class TheApp(App):
    def build(self):
        return MainWidget()

if __name__ == '__main__':
    TheApp().run()

只要给出角度并且默认旋转原点是小部件的中心,旋转本身就由小部件处理。