[英]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.