![](/img/trans.png)
[英]How to use Scatter to move paddles in the official Kivy Pong tutorial?
[英]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.