[PyGame] Rectangle keeps teleporting? - 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] Rectangle keeps teleporting? (/thread-11156.html) |
Rectangle keeps teleporting? - keyfive - Jun-25-2018 Hi, I am trying to make this cube move, but it just teleports when I let go of an arrow key. Please help! import pygame pygame.init() # screen variables sWidth = 1000 sHeight = 700 # colours red = (255, 0, 0) black = (0, 0, 0) white = (255, 255, 255) # Main mechanics gDisplay = pygame.display.set_mode((sWidth, sHeight)) clock = pygame.time.Clock() pygame.display.set_caption('Zube') def gameStart(): # Mechanics # Shapes and stuff playerStartingx = 64 playerStartingy = sHeight - 100 playerWidth = 60 playerHeight = 60 # Game Loop Variable playing = True while playing: for event in pygame.event.get(): gDisplay.fill(white) pygame.draw.rect(gDisplay, red, [playerStartingx, playerStartingy, playerWidth, playerHeight], 0) if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: playerStartingx += -50 elif event.key == pygame.K_RIGHT: playerStartingx += 50 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerStartingx += 0 pygame.display.update() clock.tick(60) gameStart() RE: Rectangle keeps teleporting? - sonnekrieger7 - Jun-27-2018 I apologize if the formatting on this isn't 100% correct, this is my first post. (Jun-25-2018, 08:41 PM)keyfive Wrote:if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: playerStartingx += 0 You can make your code simpler by taking this out. I think you thought this was speed: If the key is down, you wanted the object going 50 pixels / frame and if the key is released the object goes 0 pixels / frame. However in your code, you are changing the position each time a key is pressed. The object will move +-50 pixels if a key is pressed down and 0 pixels if the key is up. <<< and this is why you don't need this part of the code, because the object won't move anyway. When I tested the changes, the block still jumps but it is smoother. I suspect it has to do something with the for loop going through events. I think when a key is pressed it adds an event so the list just keeps getting longer. That's just a guess though because I don't have any experience with pygame. Hopefully this will help you find that bug! |