简体   繁体   中英

Ball not bouncing back in Kivy python

This is the .py file:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import Clock
from kivy.graphics import Ellipse

class Bounce(Widget):

    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.ball_size=100
        with self.canvas:
            self.ball=Ellipse(size=(self.ball_size,self.ball_size),pos=(self.center_x,self.center_y))
        Clock.schedule_interval(self.update,1/50)
    
    def update(self,dt):
        self.vx=1
        self.vy=3
        x,y=self.ball.pos
        x+=self.vx
        y+=self.vy
        if self.height<self.ball_size+y:
            self.y=-self.y
            y=self.height-self.ball_size
        self.ball.pos=(x,y)

        
    def on_size(self,*args):
        x=self.center_x-self.ball_size
        y=self.center_y-self.ball_size
        self.ball.pos=(x,y)
        
class GameApp(App):
    def build(self):
        return Bounce()

GameApp().run()

This code should return a ball going from the centre to the top and then bouncing back one time but it's not bouncing back.

You just need your code to change the self.vy<\/code> to -3<\/code> to start moving the ball down instead of up. However, your update()<\/code> method resets self.vy<\/code> every time it is called. So, the fix is to remove the resetting of self.vx<\/code> and self.vy<\/code> from the update()<\/code> method, and to set self.vy<\/code> to -3<\/code> when you want the direction to change. Here is a modified version of your Bounce<\/code> widget that does that:

class Bounce(Widget):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # initialize ball velocity
        self.vx = 1
        self.vy = 3

        self.ball_size = 100
        with self.canvas:
            self.ball = Ellipse(size=(self.ball_size, self.ball_size), pos=(self.center_x, self.center_y))
        Clock.schedule_interval(self.update, 1 / 50)

    def update(self, dt):
        x, y = self.ball.pos
        x += self.vx
        y += self.vy
        if self.height < self.ball_size + y:
            self.vy = -self.vy  # change direction of ball
            y = self.height - self.ball_size
        self.ball.pos = (x, y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM