0

I have made a top-down movement system in pygame, including acceleration and friction (the red square is the player):

import pygame
pygame.init()
running = True

x = 0
y = 0
speed = 3
friction = 10
clock = pygame.time.Clock()
FPS = 60

screen = pygame.display.set_mode((800, 650))
screen_rect = screen.get_rect()
player = pygame.Rect(25, 25, 50, 50)
player.center = (400, 325)

while running:
    deltatime = clock.tick(60) * 0.001 * FPS
    
    screen.fill((0,0,0))
    pygame.draw.rect(screen, (255,0,0), player)
    
    key = pygame.key.get_pressed()
    if key[pygame.K_a] or key[pygame.K_LEFT] == True:
        x -= speed
    if key[pygame.K_d] or key[pygame.K_RIGHT] == True:
        x += speed
    if key[pygame.K_w] or key[pygame.K_UP] == True:
        y -= speed
    if key[pygame.K_s] or key[pygame.K_DOWN] == True:
        y += speed
    x = ((100 - friction) / 100) * x
    y = ((100 - friction) / 100) * y
    player.move_ip(x / 2, y / 2)
    player.clamp_ip(screen_rect)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    pygame.display.flip()

pygame.quit()

When the player travels in one direction normally, the movement is fine. However, whenever it moves diagonally, it goes faster. Is there any way to fix this while keeping the acceleration and friction movement system the same?

0

1 Answer 1

0

When moving diagonally, you're applying an offset of magnitude speed in two directions at once for a total diagonal offset of sqrt(speed^2 + speed^2) = sqrt(2) * speed ≈ 1.414 * speed. To prevent this, just normalize the movement to have a magnitude of speed. You can store the offset in a vector and use scale_to_length to do so, or you can just divide the x and y offsets by sqrt(2) if a horizontal and vertical key are both pressed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.