[英]Ball not bouncing back in Kivy python
這是 .py 文件:
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()
此代碼應返回一個從中心到頂部的球,然后彈回一次,但它沒有彈回。
您只需要您的代碼將
self.vy<\/code>更改為
-3<\/code>即可開始將球向下而不是向上移動。
但是,您的
update()<\/code>方法在每次調用時都會重置
self.vy<\/code>
因此,修復方法是從
update()<\/code>方法中刪除
self.vx<\/code>和
self.vy<\/code>的重置,並在您希望改變方向時將
self.vy<\/code>設置為
-3<\/code> 。
這是您的
Bounce<\/code>小部件的修改版本,它可以做到這一點:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.