How can I implement on_mose_move method in pgzero?

Question:

So I’m trying to write a simple Arkanoid game, using only pgzero (!not pygame), and I want my paddle to move not using my keyboard, but using my mouse, so that the paddle moves left or right following the cursor, how can I do that and how to implement that as a class method?

I tried doing some research, watching multiple tutorials, and read documentation, it didn’t help

Asked By: maksonios

||

Answers:

on_mouse_move is a callback function that is automatically called when the mouse is moved. See Pygame Zero – Event Handling Hooks.

Minimal example of drawing a rectangle at the position of the mouse cursor:

import pgzrun

WIDTH = 400
HEIGHT = 400
rect = Rect(0, 0, 30, 30)

def draw():
    screen.fill("black")
    screen.draw.filled_rect(rect, "red")

def on_mouse_move(pos, rel, buttons):
    rect.centerx = pos[0] 
    rect.centery = pos[1] 

pgzrun.go()

Minimal example of drawing an Actor at the position of the mouse cursor:

import pgzrun

WIDTH = 400
HEIGHT = 400
actor = Actor("image_name")

def draw():
    screen.fill("black")
    actor.draw()

def on_mouse_move(pos, rel, buttons):
    actor.x = pos[0]
    actor.y = pos[1]

pgzrun.go()
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.