我试图让box2d模拟打印x& y以与库中包含的helloWorld示例类似的方式浮动到屏幕。我设法建立并链接到库。
我有一个定义一个球的类,它应该从屏幕上的一个点掉落然后掉下来。但是当我试图获得速度时,我无法访问成员数据。
objects.h内容
class Ball {
public:
bool m_contacting;
b2Body* m_body;
float m_radius;
public:
// Ball class constructor
Ball(b2World* m_world, float radius) {
m_contacting = false;
m_body = NULL;
m_radius = radius;
//set up dynamic body, store in class variable
b2BodyDef myBodyDef;
myBodyDef.type = b2_dynamicBody;
myBodyDef.position.Set(0, 20);
m_body = m_world->CreateBody(&myBodyDef);
//add circle fixture
b2CircleShape circleShape;
circleShape.m_p.Set(0, 0);
circleShape.m_radius = m_radius; //use class variable
b2FixtureDef myFixtureDef;
myFixtureDef.shape = &circleShape;
myFixtureDef.density = 1;
myFixtureDef.restitution = 0.83f;
m_body->CreateFixture(&myFixtureDef);
m_body->SetUserData( this );
m_body->SetGravityScale(5);//cancel gravity (use -1 to reverse gravity, etc)
}
~Ball(){}
};
实例化 - Ball现在应该处于模拟中
Ball* ball = new Ball(&world, 1);
balls.push_back(ball);
尝试打印身体的位置和角度。
b2Vec2 position = m_body->GetPosition();
float32 angle = m_body->GetAngle();
printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
错误消息声明m_body未在范围中声明。这似乎很明显,如果我在世界上定义一个像b2Body * body的身体;并测试代码编译并运行,但然后segfaults因为我传递了一个空引用。那么如何才能访问我的类实例的属性并将其打印出来。
我尝试过使用b2Vec2 position = Ball :: m_body-> GetPosition(); &安培; b2Vec2 position = balls-> GetPosition();但没有快乐。
答案 0 :(得分:1)
m_body是Ball类的成员,您尝试在不使用Ball对象的情况下访问它。您需要执行以下操作才能获得访问权限
ball->m_body->GetPosition();
或访问存储在向量中的Ball(假设您使用的是c ++ 11)
for(auto& b : balls)
{
(*b).m_body->GetPosition();
}
或
for(int i = 0; i < balls.size(); ++i)
{
Ball* b = balls[i];
b->m_body()->GetPosition();
}
理想情况下,您不应该使用原始指针,而应该执行
Ball ball(&world, 1)
ball.m-body->GetPosition();
或至少研究智能指针(unique_ptr)等。