仅当按下图像时如何在kivy中移动图像

how to move image in kivy only when image is pressed on

我正在 kivy 中制作游戏,我希望图像仅在按下图像时移动,但目前,如果按下屏幕上的任何位置,图像都会移动。下面是我的代码!

main.py

class Ball(Image):
velocity = NumericProperty(0)


def on_touch_down(self, touch):
    self.source = "icons/ball.png"
    self.velocity = 275
    super().on_touch_down(touch)

def on_touch_up(self, touch):
    self.source = "icons/ball.png"
    super().on_touch_up(touch)


class MainApp(App):
    GRAVITY = 300


def move_ball(self, time_passed):
    ball = self.root.ids.game_screen.ids.ball
    ball.y = ball.y + ball.velocity * time_passed
    ball.velocity = ball.velocity - self.GRAVITY * time_passed

main.kv

Ball:
        source: "icons/ball.png"
        size_hint: None, None
        size: 500, 500
        pos_hint: {"center_x": 0.5}
        id: ball

您需要确定 press 是否确实在 Image 上。为此,您可以按照 documentation:

中所述使用 collide_point()

on_touch_down(), on_touch_move(), on_touch_up() don’t do any sort of collisions. If you want to know if the touch is inside your widget, use collide_point().

所以尝试将 on_touch_down() 更改为 :

def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
        self.source = "icons/ball.png"
        self.velocity = 275
    return super().on_touch_down(touch)

on_touch_up()相似。