Box2D. b2Body object has no attribute 'GetLinearVelocity'

Viewed 168

I want to make a simple physical game with balls on Python using pygame and Box2D, but when I try to get the speed of the ball using a well-known method, I get this error. What might be the problem?

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()

The Error:

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

1 Answers

It looks like the GetLinearVelocity method is only available in the C library. The Python wrapper just uses linearVelocity:

v = player.body.linearVelocity 

For the future, if you want to know what the variable type is and what methods\properties are available, you can use the type and dir functions:

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