python 3.5 - How do I switch to constant movement when holding down a key in pygame? -
the following code set when avatar blitted screen , space bar or key tapped moves once when held down isn't moved (in air). need change code when key held down move constant.
import pygame, sys, time, random pygame.locals import * class player(duck): """the player controlled duck""" def __init__(self, x, y, width, height): super(player, self).__init__(x, y, width, height) # how many pixels player duck should move on given frame. self.y_change = 0 # how many pixels spaceship should move each frame key pressed. self.y_dist = 50 def movekeydown(self, key): """responds key-down event , moves accordingly""" if (key == pygame.k_up or key == k_space): self.rect.y -= self.y_dist def movekeyup(self, key): """responds key-up event , stops movement accordingly""" if (key == pygame.k_up or key == k_space): self.rect.y -= self.y_dist def update(self): """ moves spaceship while ensuring stays in bounds """ # moves relative current location. self.rect.move_ip(self.y_change, 0) # if spaceship moves off screen, put on. if self.rect.y <= 0: self.rect.y = 0 elif self.rect.y > window_width: self.rect.y = window_width while true: # main game loop event in pygame.event.get(): #closes game if event.type == quit: pygame.quit() sys.exit() elif event.type == pygame.keyup: player.movekeyup(event.key) elif event.type == pygame.keydown: player.movekeydown(event.key)
in movekeydown
method have set self.y_change
value desired speed , not adjust self.rect.y
value. self.rect.move_ip
call in update
method move sprite. have call update
method every frame in main while loop.
def __init__(self, x, y, width, height): super(player, self).__init__(x, y, width, height) # how many pixels player duck should move on given frame. self.x_change = 0 self.y_change = 0 # how many pixels spaceship should move each frame key pressed. self.speed = 50 def movekeydown(self, key): """responds key-down event , moves accordingly.""" if key in (pygame.k_up, pygame.k_space): self.y_change = -self.speed def movekeyup(self, key): if key in (pygame.k_up, pygame.k_space) , self.y_change < 0: self.y_change = 0 def update(self): self.rect.move_ip(self.x_change, self.y_change)
Comments
Post a Comment