【发布时间】:2021-06-28 04:17:49
【问题描述】:
我正在尝试使用 pygame 在 pybox2d 世界中绘制所有主体,但在运行代码时收到此错误消息:
pygame.draw.circle(screen, (255,0,0), position, radius)
TypeError: integer argument expected, got float
似乎 pygame 期望位置为整数,这就是错误的原因。但是,我将位置显式转换为整数,所以这应该不是问题。 该项目的代码如下: main.py
import pygame
from circle import Circle
from draw import Draw
from Box2D import b2World
PPM = 20
TARGET_FPS = 60
TIME_STEP = 1.0 / TARGET_FPS
pygame.init()
screen = pygame.display.set_mode((600, 480))
clock = pygame.time.Clock()
# A list for all of our rectangles
world = b2World(gravity=(0, 30), doSleep=True)
close = False
while not close:
for event in pygame.event.get():
if event.type == pygame.QUIT:
close = True
screen.fill((255,255,255))
circle = Circle(world,300,300,PPM)
Draw(screen,world.bodies,PPM)
world.Step(TIME_STEP, 10, 10)
pygame.display.flip()
clock.tick(TARGET_FPS)
pygame.quit()
circle.py
from Box2D import (b2FixtureDef, b2CircleShape)
class Circle:
def __init__(self, world, x, y, PPM):
self.x = x / PPM
self.y = y / PPM
self.r = 1
self.world = world
self.body = self.world.CreateDynamicBody(
position=(self.x, self.y),
fixtures=b2FixtureDef(
shape=b2CircleShape(radius = self.r), density=2.0, friction = 0.5))
draw.py
import pygame
def Circle(screen,body,fixture,PPM):
shape = fixture.shape
radius = shape.radius
position = (int(body.position.x * PPM),int(body.position.y * PPM))
pygame.draw.circle(screen, (255,0,0), position, radius)
def Draw(screen,PPM,bodies):
for body in bodies:
for fixture in body.fixtures:
try:
Circle(screen,body,fixture,PPM)
except: pass
Circle(screen,body,fixture)
我感觉这很简单,但是我不明白这段代码的问题是什么。
【问题讨论】:
-
这是
pygame.draw.circle的唯一电话吗?你确定 center 参数的组件总是整数吗? -
您可以使用integer division
//来确保您的整数不会被除法更改为浮点数。例如:self.x = x // PPM -
使用
print()检查整数是否不是浮点数
标签: python python-3.x pygame game-physics