1

I'm writing a program for school, but when I press a specific key to make my laser move across the screen, it disappears instantly. How can I make it move slowly, so the player can see it going from the left side to the right side of the screen ?

Here's the code (I wrote it again so I had only the part doing the laser moves)

#
import pygame, time
from pygame_functions import*
pygame.init()

win = pygame.display.set_mode((1440, 480))

laserImg  = pygame.image.load('laser.png')

backgroundImg = pygame.image.load('bg.jpg')

laserX = 90
laserY = 400

clock = pygame.time.Clock()

run = True
while  run:
    clock.tick(14)

    win.blit(backgroundImg, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    win.blit(laserImg, (laserX, laserY))

    if event.type ==  pygame.KEYDOWN:
        print("touche")
        if keys[pygame.K_UP]:
            while laserX < 1500:
                laserX += 10

    pygame.display.update()

pygame.quit
#

Thanks if you can help me

edit : idk why but there wasn't the line saying "while laserX < 1500"

bappi
  • 137
  • 9
  • What about having some `time.sleep(0.5)` inside the main loop? This would work but not sure this is the best approach here. – norok2 Dec 26 '19 at 13:23
  • Just move the sprite fewer pixels per clock tick. Right now you're adding 10 per 14 ticks. Try reducing that. By the way once the image is loaded from a PNG it's essentially just a sprite and it's irrelevant to your question that it happened to be loaded from a PNG. Just a nitpick, but it might help you in the future if you can abstract the concept of a sprite from the specific image file format. – Iguananaut Dec 26 '19 at 14:10

1 Answers1

1

Try something like this:

run = True
laser_moving=False
while  run:
    clock.tick(14)

     win.blit(backgroundImg, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    win.blit(laserImg, (laserX, laserY))

    if event.type ==  pygame.KEYDOWN:
        print("touche")
        if keys[pygame.K_UP]:
            laser_moving=True

    if laser_moving:
        laser_x+=1
        if laser_x > 1600:
            laser_moving=False

Your issue is that you immediately move the laser outside the screen in your loop, without waiting for the next frame to be drawn in between. You need to exit your loop so the next frame can be drawn and the intermediate states of the laser are visible.

mousetail
  • 7,009
  • 4
  • 25
  • 45