如何解决Kivy Pong游戏on_touch_move可以同时移动两个球拍
几个月前,我开始学习python,我想开始开发自己的应用程序。我选择了Kivy,并且跟随this tutorial。
本教程使用以下代码来添加触摸和移动:
def on_touch_move(self,touch):
if touch.x < self.width / 1 / 4:
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4:
self.player2.center_y = touch.y
当我使用此代码时,我的两个拨片同时移动。我加了一些括号:
def on_touch_move(self,touch):
if touch.x < self.width / (1 / 4):
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4:
self.player2.center_y = touch.y
此后,我能够移动左桨,但我的右桨也移动了。
我最终使用了来自kivy网站的代码,该代码确实有效:
def on_touch_move(self,touch):
if touch.x < self.width/3:
self.player1.center_y = touch.y
if touch.x > self.width - self.width/3:
self.player2.center_y = touch.y
有人可以解释为什么一个代码可以正常运行,为什么另一个不能正常运行吗? 预先感谢!
解决方法
如果您的条件不同于Kivy的条件,那么它们将不会同时返回true。
让我们看看您的代码:
def on_touch_move(self,touch):
if touch.x < self.width / (1 / 4):
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4:
self.player2.center_y = touch.y
# which simplifies to ↓ because dividing by a quarter is the same as multiplying by four
def on_touch_move(self,touch):
if touch.x < self.width * 4: # will always be true (checking if touching anywhere on 4 times the screen width)
self.player1.center_y = touch.y
if touch.x > self.width * 3 / 4: # checking if touching last quarter of screen
self.player2.center_y = touch.y
现在让我们简化Kivy的代码:
def on_touch_move(self,touch):
if touch.x < self.width / 3: # checking if touching first third of screen
self.player1.center_y = touch.y
if touch.x > self.width * 2 / 3: # checking if touching last third of screen
self.player2.center_y = touch.y
如您所见,您的第一个if语句始终处于触发状态,因此您可能希望将其更改为:if touch.x < self.width * 1 / 4:
它将检查第一季度
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。