简体   繁体   English

Pygame 不允许我使用 float 进行 rect.move,但我需要它

[英]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.\我最近在 Python 3 和 Pygame 中重新创建了 月球着陆器的一个版本(你知道,旧的复古游戏):由于重力,我的着陆器沿 y 轴移动( rect.move )每一帧。\

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.在我达到 1 m/s 之前,添加到 rect.move 的 y 值是一个低于 1 的浮点数:我必须使用int()对其进行四舍五入,因为 pygame 不喜欢浮点数。
In a previous version with Tkinter, the y coord of the lander was like this:在之前的 Tkinter 版本中,着陆器的 y 坐标是这样的:

0.01
0.02
...
0.765
1.03
1.45
...

In pygame it's在 pygame 它是

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 ?比如,输入一个浮点数到rect.move Thanks in advance!提前致谢!

Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data:由于pygame.Rect应该代表屏幕上的一个区域,因此pygame.Rect object 只能存储积分数据:

The coordinates for Rect objects are all integers. Rect 对象的坐标都是整数。 [...] [...]

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. 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 (eg .topleft ) of the rectangle:将坐标round并将其分配给矩形的位置(例如.topleft ):

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

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)我自己没有测试过,所以如果这不起作用,我很抱歉,但我认为 python 将数字作为字符串而不是int(variable)

You should do float(variable)你应该做float(variable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM