C
C
coi17512019-01-02 14:13:53
Python
coi1751, 2019-01-02 14:13:53

How to do braking physics in pygame (Python)?

It became interesting to play with writing mini toys .. and since the subject of my study is Python, I chose the pygame library. I want to make braking physics so that when you release the button, for example to the right, the character (still a cube) does not stop immediately, but after a little "driving".

for i in pygame.event.get():
        if i.type == pygame.QUIT:
            work = False
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_LEFT] and Player.x > 0:
        Player.x -= Player.speed
    if keys[pygame.K_RIGHT] and Player.x < 640 - Player.width:
        Player.x += Player.speed

Here I receive the event of pressing the left and right arrow keys, that is, pressed - the character moves to Player.speed, released - does not move. How to implement so that when the key is released, the fading cube moves further, and does not stop instantly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2019-01-02
@coi1751

To do this, you just need to study physics of the 8th grade.
Acceleration = 0
User presses the button - Acceleration = N (distance units / unit time 2 )
Releases - acceleration = 0
Deceleration will be some kind of constant. Let it be N / 2. This is an imitation of some kind of friction force.
Each tick you increase the speed by (acceleration - deceleration) * (tick time / your unit of time)
If the speed is 0, then the deceleration is replaced by zero
If you need to instantly set the speed when you press it, you process it separately.
The maximum speed limit (if any) must also be handled

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question