1

I'm a little bit new to Pygame, and I'm working on a platformer. When I wrote the code for adding velocity and movement I was a little bit confused on why a positive velocity and a negative movement were treated differently. I copied over some code and managed to isolate the problem. It's been bugging me as I fixed and added more to the platformer because it worked perfectly fine except for this one part.

import pygame, sys
pygame.init()

SCREEN_SIZE = (500, 500)
screen = pygame.display.set_mode(SCREEN_SIZE)
clock = pygame.time.Clock()

happyGuy = pygame.rect.Rect(250, 250, 50, 50)
vel = 0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.exit()
            sys.exit()
            
    inputs = pygame.key.get_pressed()
    if inputs[pygame.K_a]: vel -= 6
    if inputs[pygame.K_d]: vel += 6
        
    vel *= 0.8 # Friction
    vel = round(vel * 1000) / 1000
    print(vel)
    if vel > 0:
        if vel < 0.01: vel = 0
    if vel < 0:
        if vel > -0.01: vel = 0
    # if abs(vel) < 0.01: vel = 0
        
    happyGuy.x += vel
    screen.fill((255, 255, 255))
    pygame.draw.rect(screen, (255, 0, 0), happyGuy)
    pygame.display.flip()
    clock.tick(30)
    

This code should move the player left and right when A or D are pressed. Both ways are expected to act the same when pressing them, unless I messed something up. Please help and thank you :)

Romo
  • 11
  • 1
  • 1
    I ran your code. When I press A, the square moves to the left. When I press D, it moves to the right. What is the problem you are facing? – JustLearning Nov 08 '22 at 19:50
  • The problem is the different speed for left and right. The reason is that a `pygame.Rect` object can only store integer data (`happyGuy` is a `pygame.Rect`). Therefore the movement to the left is faster than the movement to the right. The solution is explained in the answer to [Pygame doesn't let me use float for rect.move, but I need it](https://stackoverflow.com/questions/63468413/pygame-doesnt-let-me-use-float-for-rect-move-but-i-need-it) . – Rabbid76 Nov 08 '22 at 19:51

0 Answers0