gpt4 book ai didi

c++ - Box2d C++ AccessViolation 使用 b2fixture out 方法

转载 作者:行者123 更新时间:2023-11-30 04:25:22 24 4
gpt4 key购买 nike

我正在创建 box2d 多边形,我想在将夹具附加到主体的方法之外创建夹具,但是当我这样做时,我遇到了访问冲突。

我已经逐步完成了代码,box2d 肯定正在获取 fixture 对象。

当我在方法内将夹具附加到主体时,它工作正常。当我尝试调用方法时,它抛出访问冲突错误

    b2FixtureDef* LineSegment::GenerateFixture(b2Vec2 vertices[4],b2Body* body,b2World* world){
b2BodyDef bodyDef;
//bodyDef.type = b2_kinematicBody;
bodyDef.position.Set(_currentStepStartPosition.x,_currentStepStartPosition.y);
body =world->CreateBody(&bodyDef);
int32 count = 4;
b2PolygonShape polygon;
polygon.Set(vertices, count);
b2FixtureDef fixtureDef2;
fixtureDef2.shape = &polygon;
fixtureDef2.density = 1.0f;
fixtureDef2.friction = 0.3f;
body->CreateFixture(&fixtureDef2);/// works if i attatch the fixture here here
return &fixtureDef2;
}

当我在此处附加夹具时调用方法失败

    bool LineSegment::GenerateNextBody(b2Body* retBody){
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(_currentStepStartPosition.x,_currentStepStartPosition.y);
retBody =world->CreateBody(&bodyDef);
_currentStep++;
b2Vec2 vertices[4];
if(_inclinePerStep != 0){
GetVertsInclineSquare(vertices,_stepWidth,_thickness,_inclinePerStep);
}else{
GetVertsSquare(vertices,_stepWidth,_thickness);
}
if(_currentStep == 1){
_GameWorldVerticies[0] =b2Vec2((_currentStepStartPosition.x+vertices[0].x)*PTM_RATIO,(_currentStepStartPosition.y+vertices[0].y)*PTM_RATIO);
_GameWorldVerticies[3] =b2Vec2((_currentStepStartPosition.x+vertices[3].x)*PTM_RATIO,(_currentStepStartPosition.y+vertices[3].y)*PTM_RATIO);

}
b2FixtureDef* fixture = GenerateFixture(vertices,retBody,world);

//retBody->CreateFixture(fixture); throws a access violation if i attatch the fixture here
_currentStepStartPosition.x += vertices[2].x+(vertices[2].x);
_currentStepStartPosition.y +=(_inclinePerStep/2);
if(_steps <= _currentStep){
_GameWorldVerticies[1] =b2Vec2((_currentStepStartPosition.x+vertices[1].x)*PTM_RATIO,(_currentStepStartPosition.y+vertices[1].y)*PTM_RATIO);
_GameWorldVerticies[2] =b2Vec2((_currentStepStartPosition.x+vertices[2].x)*PTM_RATIO,(_currentStepStartPosition.y+vertices[2].y)*PTM_RATIO);
return false;
}
return true;
}

更新

新片段

        b2FixtureDef* fixtureDef2 = new b2FixtureDef();
fixtureDef2->shape = &polygon;
fixtureDef2->density = 1.0f;
fixtureDef2->friction = 0.3f;
//body->CreateFixture(&fixtureDef2);/// works if i attatch the fixture here here
return fixtureDef2;

最佳答案

问题是您在 GenerateFixture 中返回了一个指向局部变量的指针,这是未定义的行为。变量 fixtureDef2 在栈上,当函数返回时,栈的那个区域不再有效。当您稍后调用 CreateFixture 函数时,指针现在将指向那个函数的堆栈区域。

要解决这个问题,您可以在堆上创建它,例如

关于c++ - Box2d C++ AccessViolation 使用 b2fixture out 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12195129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com