盒子2D。b2Body 对象没有属性 'GetLinearVelocity'



我想使用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:projsbox2dbonkmain.py", line 60, in <module>
keyIsDown(pygame.key.get_pressed())
File "D:projsbox2dbonkmain.py", line 35, in keyIsDomn
v = player.body.GetLinearVelocity()
AttributeError: 'b2Body' Object has no attribute 'GetLinearVelocity'

错误的屏幕截图

看起来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',...]

最新更新