Box2D。b2Body对象没有属性“GetLinearVelocity”

2024-10-01 13:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用pygame和Box2D在Python上制作一个简单的物理游戏,但是当我尝试使用一个众所周知的方法来获得球的速度时,我得到了这个错误。有什么问题吗

class Ball:
    def __init__(self, x, y, radius, world, color, fric=0.3, maxspeed=20, density=0.01, restitution=0.5):
        self.x = x
        self.y = y
        self.radius = radius
        self.fric = fric
        self.maxspeed = maxspeed
        self.density = density
        self.restitution = restitution
        self.color = color

        #body
        self.bodyDef = box2d.b2BodyDef()
        self.bodyDef.type = box2d.b2_dynamicBody
        self.bodyDef.position = (x, y)

        self.body = world.CreateBody(self.bodyDef)

        #shape
        self.sd = box2d.b2CircleShape()
        self.sd.radius = radius

        #fixture
        self.fd = box2d.b2FixtureDef()
        self.fd.shape = self.sd


        #phys params
        self.fd.density = density
        self.fd.friction = fric
        self.fd.restitution = restitution

        self.body.CreateFixture(self.fd)

player = Ball(width / 3, height / 2, 30, world, (150, 150, 150))

v = player.body.GetLinearVelocity()

错误:

Traceback (most recent call last):
  File "D:\projs\box2d\bonk\main.py", line 60, in <module>
    keyIsDown(pygame.key.get_pressed())
  File "D:\projs\box2d\bonk\main.py", line 35, in keyIsDomn
    v = player.body.GetLinearVelocity()
AttributeError: 'b2Body' Object has no attribute 'GetLinearVelocity'

screenshot of error


Tags: selfworldbodysddensitycolorplayerfd
1条回答
网友
1楼 · 发布于 2024-10-01 13:32:10

看起来GetLinearVelocity方法仅在C库中可用。Python包装器只使用linearVelocity

v = player.body.linearVelocity 

将来,如果您想知道变量类型以及可用的方法\属性,可以使用typedir函数:

print(type(player.body))  # class name  # <class 'Box2D.Box2D.b2Body'>
print(dir(player.body))   # all methods and properties  # ['ApplyAngularImpulse', 'ApplyForce',....,'linearVelocity',...]

相关问题 更多 >