Search code examples
pythonkivykivy-language

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


I'm making a game in kivy and I would like for an image to move only when the image is pressed on, but currently, the image moves if anywhere in the screen is pressed. Below is my code!

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

Solution

  • You need to determine if the press is actually on the Image. To do that you can use collide_point() as described in the documentation:

    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().

    So try changing on_touch_down() to :

    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)
    

    And similar with on_touch_up().