首页 > 解决方案 > 在pygame中绘制圆圈时出现TypeError

问题描述

我正在尝试使用 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()

圈子.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))

绘制.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)

我觉得这很简单,但我不明白这段代码中的问题是什么。

标签: pythonpython-3.xpygamegame-physics

解决方案


中心参数的组件pygame.draw.circle必须是整数。round该坐标:

pygame.draw.circle(screen, (255,0,0), position, radius)

pygame.draw.circle(screen, (255,0,0), (round(position[0]), round(position[1])), radius)

推荐阅读