Python Arcade – Handling Mouse Inputs
Last Updated :
23 Sep, 2021
In this article, we will learn how we can handle mouse inputs in the arcade module in Python.
In Arcade, you can easily handle the mouse inputs using these functions:
on_mouse_motion():
Syntax: on_mouse_motion(x, y, dx, dy)
Parameters:
- x : x coordinate
- y : y coordinate
- dx : change in x coordinate
- dy : change in y coordinate
on_mouse_press():
Syntax : on_mouse_press( x, y, button, modifiers)
Parameters:
- x : x coordinate
- y : y coordinate
- button : button that is pressed
- modifiers : Bitwise ‘and’ of all modifiers (shift, ctrl, num lock) pressed during this event.
on_mouse_motion() function will be called whenever the user moves the mouse. Similarly, on_mouse_press() will be called whenever a user presses a mouse button.
Movement using Mouse Inputs
Here we will create a simple program using the arcade module to move our character using mouse inputs.
In the below example, we are going to create a MainGame() class. Inside this class first, we will initialize the starting x and y coordinate of the player. Then we will create three functions inside this class.
- on_draw():- Inside this function, we will start the rendering using arcade.start_render() and then we will draw our player.
- on_mouse_motion():- This function will be called whenever the user moves the mouse. Inside this function, we will change the x and y coordinate of the player.
Below is the implementation:
Python3
import arcade
class MainGame(arcade.Window):
def __init__( self ):
super ().__init__( 600 , 600 , title = "Keyboard Inputs" )
self .x = 100
self .y = 100
def on_draw( self ):
arcade.start_render()
arcade.draw_circle_filled( self .x, self .y, 25 ,
arcade.color.GREEN)
def on_mouse_motion( self , x, y, dx, dy):
self .x = x
self .y = y
MainGame()
arcade.run()
|
Output:
Handle Mouse Clicks
Now to handle mouse clicks we are going to create a new function called “on_mouse_press”. This function will be called every time user clicks a mouse button.
Python3
import arcade
class MainGame(arcade.Window):
def __init__( self ):
super ().__init__( 600 , 600 , title = "Keyboard Inputs" )
self .x = 100
self .y = 100
def on_draw( self ):
arcade.start_render()
arcade.draw_circle_filled( self .x, self .y, 25 ,
arcade.color.GREEN )
def on_mouse_motion( self , x, y, dx, dy):
self .x = x
self .y = y
def on_mouse_press( self , x, y, button, modifiers):
print ( "Mouse button is pressed" )
MainGame()
arcade.run()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...