繁体   English   中英

Kivy Pong Game on_touch_move 同时移动两个球拍

[英]Kivy Pong Game on_touch_move moves both paddles simoultanouesly

几个月前我开始学习 python,我想开始开发自己的应用程序。 我选择了 Kivy 并且我正在跟随本教程

本教程使用以下代码添加触摸和移动:

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

有人可以解释为什么一个代码运行正常,为什么另一个没有? 提前致谢!

您的 if 条件与 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:这将检查第一季度

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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