Pygame doesn’t let me use float for rect.move, but I need it

I’ve recently recreated a version of Lunar Lander (you know, the old retro game) in Python 3 and Pygame: my lander moves (̀̀̀rect.move) each frame along the y axis because of gravity.

Problem:
Until I hit 1 m/s, the y value added to rect.move is a float under 1: I must use int() to round it up, as pygame doesn’t like floats.
In a previous version with Tkinter, the y coord of the lander was like this:

0.01
0.02
...
0.765
1.03
1.45
...

In pygame it’s

0
0
0
...
1
1
1
2
2
...

This is really annoying, as the movement isn’t fluid.
Does someone know how to solve this? Like, input a float to rect.move?
Thanks in advance!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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. […]

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location (e.g. .topleft) of the rectangle:

x, y = # floating point coordinates
rect.topleft = round(x), round(y)

Method 2

I haven’t tested it myself so I am sorry if this does not work but I think python is taking the number as a string so instead of
int(variable)

You should do float(variable)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x