0

I'd like to make a program so that bullets can be fired when I press the x key. I made my own code. I want one bullet to fly when I press it, not when I press it hard. When you press the x key, the bullet should fly naturally, but the position suddenly changes and you teleport. please help me. here is my code

while True:
    clock.tick(100)
    pressed = pygame.key.get_pressed()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if pressed[pygame.K_LEFT] or pressed[pygame.K_RIGHT]:
                last_direction_key = event.key
            if pressed[pygame.K_DOWN] or pressed[pygame.K_UP]:
                last_key = event.key
        if pressed[pygame.K_x]:
            bullet_x += 10

Bullet_x is the horizontal position variable of the bullet. How can I make it fly away naturally?

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
조수민
  • 27
  • 3
  • I learned pygame long time ago, I don't remember much of it but I am pretty sure that this tutorial can help your situation, cause it cantains shooting bullets. here is the link to the website or its youtube channel: [website](https://techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/), youtube channel [youtube channel](https://www.youtube.com/watch?v=i6xMBig-pP4) – Shoaib Mirzaei Oct 14 '20 at 07:21

1 Answers1

1

Like Shoaib Mirzaei said, that Tech With Tim tutorial is very good for beginning with python and pygame, and there are many other such tutorials around.

To fix your current code, you need a new variable, call it something like shooting and set it to False at the start of the program:

shooting = False

Then, once x is pressed, set shooting to True:

if pressed[pygame.K_x]:
    shooting = True

Make sure that is indented in line with the other two button press checks. Now, just check if shooting is True and move the bullet:

if shooting:
    bullet_x += 10

This should be indented so it runs in the while loop.

Now, this will work fine with 1 bullet, but as you start to get a more complex game, you may want to use a Class to control your bullets. This is something you can Google for yourself later if you so need.

Resistnz
  • 74
  • 5