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
CodePudding user response:
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))
CodePudding user response:
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.