问题描述
我想用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,(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'
解决方法
看来GetLinearVelocity
方法仅在C库中可用。 Python包装器仅使用linearVelocity
:
v = player.body.linearVelocity
将来,如果您想知道变量类型是什么以及可用的方法\属性,可以使用type
和dir
函数:
print(type(player.body)) # class name # <class 'Box2D.Box2D.b2Body'>
print(dir(player.body)) # all methods and properties # ['ApplyAngularImpulse','ApplyForce',....,'linearVelocity',...]