[PyGame] Keep moving pressing a key - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Game Development (https://python-forum.io/forum-11.html) +--- Thread: [PyGame] Keep moving pressing a key (/thread-19658.html) |
Keep moving pressing a key - alexponceal - Jul-09-2019 I've started to use PyGame a few days ago and I'm trying to create some games. I'd like to add that I was reading the PyGame documentation (that didn't help me at all) and the book "Making Games With Python and Pygame". My objective is to code a continuous movement. However, as a result, I get a program that moves the sprite one step at once. Here is my script: # -*- coding: utf-8 -*- import pygame, sys from pygame.locals import * # Clases generadas from jugador import Jugador pygame.init() # -------------------------- VARIABLES GLOBALES -------------------------- # Configuración VENANCHO = 1366 VENALTO = 768 # Colores R G B NEGRO = ( 0, 0, 0) BLANCO = (255, 255, 255) ROJO = (255, 0, 0) # Creación de la ventana VENTANA = pygame.display.set_mode((VENANCHO, VENALTO), pygame.FULLSCREEN) pygame.display.set_caption('Neav') # Generar lista de sprites lista_de_sprites = pygame.sprite.Group() perJugador = Jugador(ROJO, 40, 40) perJugador.rect.x = VENANCHO / 2 perJugador.rect.y = VENALTO / 2 VELOCIDAD = 40 # Añadir al jugador a la lista de sprites lista_de_sprites.add(perJugador) while True: for event in pygame.event.get(): VENTANA.fill(BLANCO) if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_RIGHT: perJugador.moveRight(VELOCIDAD) elif event.key == K_LEFT: perJugador.moveLeft(10) elif event.key == K_DOWN: perJugador.moveDown(10) elif event.key == K_UP: perJugador.moveUp(10) lista_de_sprites.update() lista_de_sprites.draw(VENTANA) pygame.display.flip()The object perJugador is created from this class: import pygame # Colores R G B BLANCO = (255, 255, 255) class Jugador(pygame.sprite.Sprite): def __init__(self, color, ancho, alto): super().__init__() pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((ancho, alto)) self.image.fill(BLANCO) self.image.set_colorkey(BLANCO) pygame.draw.rect(self.image, color, (0, 0, ancho, alto)) self.rect = self.image.get_rect() def moveRight(self, pixels): self.rect.x += pixels def moveLeft(self, pixels): self.rect.x -= pixels def moveDown(self, pixels): self.rect.y += pixels def moveUp(self, pixels): self.rect.y -= pixelsIs there another way to make movement properly with the sprites and sprite module? Thanks a lot for your answers guys. RE: Keep moving pressing a key - Windspar - Jul-09-2019 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() keys = pygame.key.get_pressed() if keys[pygame.K_UP]: perJugador.moveUp(10) if keys[pygame.K_DOWN]: perJugador.moveDown(10) # and etc |