Because we are going to be shooting bullets left or right we need to ensure our character is always facing left or right. This required modifying the player.draw method and adding another attribute of standing to our player.
We also need to modify our main loop to ensure our character is always facing left or right.
man=player(200,410,64,64)run=Truewhilerun:clock.tick(27)foreventinpygame.event.get():ifevent.type==pygame.QUIT:run=Falsekeys=pygame.key.get_pressed()ifkeys[pygame.K_LEFT]andman.x>man.vel:man.x-=man.velman.left=Trueman.right=Falseman.standing=False# NEWelifkeys[pygame.K_RIGHT]andman.x<500-man.width-man.vel:man.x+=man.velman.right=Trueman.left=Falseman.standing=False# NEWelse:main.standing=True# NEW (removed two lines)man.walkCount=0ifnot(man.isJump):ifkeys[pygame.K_UP]:man.isJump=Trueman.right=Falseman.left=Falseman.walkCount=0else:ifman.jumpCount>=-10:neg=1ifman.jumpCount<0:neg=-1man.y-=(man.jumpCount**2)*0.5*negman.jumpCount-=1else:man.isJump=Falseman.jumpCount=10redrawGameWindow()
Setting up The Projectiles
The first step is to create a list which will store all of our bullet objects.
bullets=# This goes right above the while loop
Now we are going to add a for loop into our main loop that will move our bullets and remove them if they have left the screen.
# Goes inside the while loopforbulletinbullets:ifbullet.x<500andbullet.x>0:bullet.x+=bullet.vel# Moves the bullet by its velelse:bullets.pop(bullets.index(bullet))# This will remove the bullet if it is off the screen
Shooting the Bullet
We are first going to change our jump key to be the up arrow (just change pygame.K_SPACE to pygame.K_UP). Then we are going to create a new if statement that will check if the space bar is clicked. If it is we will create a new bullet, give it a velocity and start moving it.
# Goes inside the while loop, under keys = ...ifkeys[pygame.K_SPACE]:ifman.left:facing=-1else:facing=1iflen(bullets)<5:# This will make sure we cannot exceed 5 bullets on the screen at oncebullets.append(projectile(round(man.x+man.width//2),round(man.y+man.height//2),6,(0,0,0),facing))# This will create a bullet starting at the middle of the character
And the last thing to do is to draw our bullets inside redrawGameWindow().