Monday, August 23, 2021

kv 39 moving ball

#widget3.py
from kivy.app import App
from kivy.graphics import Ellipse
from kivy.metrics import dp
from kivy.properties import Clock
from kivy.uix.widget import Widget


class Widget3(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.ball_size = dp(50)
        self.vx = 3
        self.vy = 3
        with self.canvas:
            self.ball = Ellipse(pos=self.center, size=(self.ball_size, self.ball_size))

        Clock.schedule_interval(self.update, 0.01)

    def on_size(self, *args):
        self.ball.pos = (self.center_x-self.ball_size/2, self.center_y-self.ball_size/2)

    def update(self, dt):
        x, y = self.ball.pos

        x += self.vx
        y += self.vy

        if y + self.ball_size > self.height:
            y = self.height  - self.ball_size
            self.vy = -self.vy
        if x + self.ball_size > self.width:
            x = self.width - self.ball_size
            self.vx = -self.vx
        if y < 0:
            y = 0
            self.vy = -self.vy
        if x < 0:
            x = 0
            self.vx = -self.vx

        self.ball.pos = (x,y)


class Widget3App(App):
    def build(self):
        return Widget3()


Widget3App().run()

reference:
 

No comments:

Post a Comment