Python Arcade – Adding Bullets in Game
In this article, we will learn how to add bullets to a game in Arcade using Python.
In this example, we are going to add bullets to the screen. For this, we will use some functions:
draw_text(): This function is used to draw text to the screen using Pyglet’s label.
Syntax: arcade.draw_text(text, x, y, color, size, width, align, font_name)
- text: Text we want to display
- x : x coordinate
- y : y coordinate
- color : color of the text
- size : Size of the font
- width : Width of the text
- align : Alignment of the text
- font_name : Name of the font
PhysicsEnginePlatformer(): Simplistic physics engine for use in a platformer.
Syntax: arcade.PhysicsEnginePlatformer( player_sprite , platforms, gravity, ladders)
- player_sprite: sprite of the player
- platforms: The sprites it can’t move through
- gravity: Downward acceleration per frame
- ladders: Ladders the user can climb on
In the below example, we are going to create a MainGame() class. Inside this class first, we are going to initialize some variables for velocity, scene, bullet sprite, and player’s sprite then we will create 4 functions inside this class.
- on_draw(): Inside this function, we will use our scene on the screen.
- setup(): In this function, we will initialize our scene object then we will load our player and platform’s sprites. After that, we will call the PhysicsEnginePlatformer() function.
- on_update(): In this function, we will update the physics engine, x coordinates of the player’s sprite, and bullet y-coordinate.
- on_key_press() and on_key_release(): In this function, we will change the value of the velocity variable according to the keyboard key that is pressed or released. When the user presses the down arrow key then we will load our bullet sprite.
Below is the implementation: