Kivy和collide_widget无法正常工作

时间:2016-07-15 12:38:30

标签: python python-3.x collision-detection kivy kivy-language

我正在使用Python和Kivy创建一个Breakout游戏(也可以使用Python Book中的“帮助”)。

流程是:游戏构建(小部件被创建并放置到位),时钟开始并定期运行更新以更新玩家和球的位置。

当球与球拍碰撞时,它会起作用!它会反弹并按预期改变速度。然而,当球接近块时,它直接穿过它们,而不是认识到那里甚至有小部件!任何人都能看到我错过的明显事物吗?

我附上了一些代码:

class Ball(Widget):
    def update(self,dt):
        #code not included which updates velocity ( works )
        self.bounce_from_player(self.parent.player) #this works

    def bounce_from_player( self,player ):
        if self.collide_widget(player):
        #code not included which update velocity ( works )
            self.parent.destroy_blocks(self) #this doesn't work (below)


class Game(FloatLayout):
    blocks=ListProperty([])
    player=ObjectProperty([])
    ball=ObjectProperty([])

    def setup_blocks( self ):
        self.blocks=[]
        for y_jump in range(5):
            for x_jump in range(10):
                block=Block(pos_hint={'x':0.05+0.09*x_jump,'y':0.55+0.09*y_jump})
                block.colour=random.choice([(0.78,0.28,0),(0.28,0.63,0.28),(0.25,0.28,0.78)])
                self.add_widget(block)
                self.blocks.append(block)

    def update( self,d t):
        self.ball.update(dt) 
        self.player.update(dt) #code not included - this works

    def start( self,*args ):
        Clock.schedule_interval(self.update,1./60.)

    def destroy_blocks( self,ball ): #doesn't work
        for block in enumerate(self.blocks):
            if ball.collide_widget(block):
                y_overlap=(ball.top - block.y if ball.velocity[1]>0 else block.top - ball.y)/block.size_hint_y
                x_overlap=(ball.right - block.x if ball.velocity[0]>0 else block.right - ball.x)/block.size_hint_x
                if x_overlap<y_overlap:
                    ball.velocity[0]*=-1
                else:
                    ball.velocity[1]*=-1
                    self.remove_widget(block)
                if len(self.blocks)==0:
                    self.win()
                return #remove 1 block per frame

0 个答案:

没有答案
相关问题