0

so whenever i move my player to the left i move soo fast but when i move to the right i move very slow, although the speed is the same, i implemented delat time and it still is the same?? here is my code:

    if sticky_keys:
            if collide_sides == False:
                if move_left != '':
                    if kb.is_pressed(move_left):
                        rect[0].x -= speed * dt
                if move_right != '':
                    if kb.is_pressed(move_right):
                        rect[0].x += speed * dt 
                if move_up != '':
                    if kb.is_pressed(move_up):
                        rect[0].y -= speed * dt
                if move_down != '':
                    if kb.is_pressed(move_down):
                        rect[0].y += speed * dt
                if jump != '':
                    if jumped:
                        rect[0].y -= jump_velocity
                        jump_velocity -= 1
                        if jump_velocity < - 20:
                            jumped = False
                            jump_velocity = 20
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Morris
  • 55
  • 6

2 Answers2

1

See Pygame doesn't let me use float for rect.move, but I need it. Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the movement gets lost when the movement is add to the position of the rectangle. As a result, one moves to the left faster than to the right:

int(10 - 1.5) == 8
int(10 + 1.5) == 11

Store the position twice. Once with floating point accuracy in pos_x and pos_y and in integral in rect[0]. Change pos_x and pos_y and finally update rect[0]with the rounded position.

Initialization before the application loop:

pos_x, pos_y = rect[0].topleft

In the application loop:

if move_left != '':
    if kb.is_pressed(move_left):
        pos_x -= speed * dt
if move_right != '':
    if kb.is_pressed(move_right):
        pos_x += speed * dt 
if move_up != '':
    if kb.is_pressed(move_up):
        pos_y -= speed * dt
if move_down != '':
    if kb.is_pressed(move_down):
        pos_y += speed * dt
rect[0].topleft = (round(pos_x), round(pos_y))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

From this code it is hard to tell, however I assume it's a rounding error with pygame.Rect. pygame.Rect can only store int values, but you're most likely providing float values.

ByteTh1ef
  • 71
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 03 '22 at 04:15