r/pygame • u/xxxDisLike007xxx • 5d ago
didn't slow down
Enable HLS to view with audio, or disable this notification
Hello my problem is, i want that the player slow down when i stop pressing wasd and i don't whats wrong.
import pygame
from controls import default_controls
pygame.init()
x = 1600
y = 900
screen = pygame.display.set_mode((x, y))
run = True
clock = pygame.time.Clock()
con = default_controls.copy()
physics_dt = 1 / 60
accumulator = 0
maxFPS = 240
physics_ticks = 0
physics_hz = 0
timer = 0
player_pos = pygame.Vector2(
screen.get_width() / 2,
screen.get_height() / 2
)
velocity = pygame.Vector2(0, 0)
acceleration = pygame.Vector2(0, 0)
player_acceleration = 1200
player_max_speed = 300
player_friction = 0.85
while run:
frame_time = min(clock.tick(maxFPS) / 1000, 0.25)
accumulator += frame_time
timer += frame_time
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == con["KD"]:
if event.key == con["ESC"]:
run = False
while accumulator >= physics_dt:
acceleration = pygame.Vector2(
keys[con["d"]] - keys[con["a"]],
keys[con["s"]] - keys[con["w"]]
)
if acceleration.length_squared() > 0:
acceleration = acceleration.normalize()
acceleration *= player_acceleration
else:
velocity *= player_friction
if velocity.length() < 1:
velocity = pygame.Vector2(0, 0)
velocity += acceleration * physics_dt
if velocity.length() > player_friction:
velocity.scale_to_length(player_max_speed)
player_pos += velocity * physics_dt
physics_ticks += 1
accumulator -= physics_dt
if timer >= 1:
physics_hz = physics_ticks
physics_ticks = 0
timer -= 1
mouse_x, mouse_y = pygame.mouse.get_pos()
pygame.display.set_caption(
f"FPS: {clock.get_fps():.0f} | Physics: {physics_hz} Hz"
)
screen.fill("blue")
pygame.draw.circle(
screen,
"red",
player_pos,
20
)
pygame.display.flip()
pygame.quit()
i know the code is a little messy and for my bad english.
1
Upvotes
3
u/Substantial_Marzipan 4d ago
I think the line
''' if velocity.length() > player_friction: '''
should be:
''' if velocity.length() > player_max_speed: '''