问题
am having one car and one bike object. at the time of collison detction. i need to get which(Car or bike) is colliding with wall. for that am using body->getuserdata . but it always returns null. am confuse d that why am getting null. were am wrong?
i refer this link but same as i did. not useful.
Code for car:-
sprintf(temp,CAR_BODY_CAR_PLIST);
m_Texture[2] = new TextureObject(temp,spritesheet1,1,true,kTexture2DPixelFormat_Default,2);
// add cart //
b2BodyDef bodyDef;
b2FixtureDef fixtureDef;
b2PolygonShape polygonShape;
b2CircleShape circleShape;
bodyDef.position.Set(startPos.x,startPos.y);
bodyDef.type = b2_dynamicBody;
**bodyDef.userData = m_Texture[2];**
cart = m_world->CreateBody(&bodyDef);
fixtureDef.density = 25.0f;
fixtureDef.friction = 0.3f;
fixtureDef.restitution = 0.1f;
fixtureDef.filter.categoryBits = 0x0008;
fixtureDef.filter.maskBits = 0x0003;
fixtureDef.density = 0.0f;
fixtureDef.isSensor = true;
b2Vec2 points[6] =
{
b2Vec2(0.7f,0.0f),
b2Vec2(0.7f,3.25f),
b2Vec2(-0.7f,3.25f),
b2Vec2(-0.7f,0.0f),
};
polygonShape.Set(points,4);
m_RiderTest = cart->CreateFixture(&fixtureDef);
((GroundTestCallback*)m_GroundRayCastTest)->addIgnoreFixture(m_RiderTest);
fixtureDef.isSensor = false;
fixtureDef.density = 25.0f;
fixtureDef.filter.categoryBits = 0x0010;
fixtureDef.filter.maskBits = 0x0007;
polygonShape.SetAsBox(TEST_SCALE*0.4f, TEST_SCALE*0.15f, axel1Pos, axel1Angle);
((TestCallback*)Test)->addIgnoreFixture(cart->CreateFixture(&fixtureDef));
polygonShape.SetAsBox(0.4f*axel2Length, TEST_SCALE*0.15f, axel2Pos, axel2Angle);
((TestCallback*)Test)->addIgnoreFixture(cart->CreateFixture(&fixtureDef));
texture class:-
TextureObject::TextureObject(char *texturename,CCNode *layer, int zOrder, bool isFrameCache,CCTexture2DPixelFormat pixFormat, int tag)
{
CCTexture2D::setDefaultAlphaPixelFormat(pixFormat);
CCSprite *newSprite = CCSprite::createWithSpriteFrameName(texturename);
m_Layer = layer;
m_Layer->addChild(newSprite,zOrder);
newSprite->setTag(tag);
m_Texture = newSprite;
CCTexture2D::setDefaultAlphaPixelFormat(kTexture2DPixelFormat_Default);
}
at wall class:-(Detecting collison detction)
bool wall::HandleBeginContact(b2Fixture *fixtureA,b2Fixture *fixtureB)
{
b2Fixture *myFixture = m_MainCollision->GetFixtureList();
if(myFixture == fixtureA || myFixture == fixtureB )
{
b2Body *bodyA = myFixture->GetBody();
**CCSprite *sprite = (CCSprite *) bodyA->GetUserData();** // spriteA am getting null
CCLog("spritea = %d",sprite->getTag());
if (sprite->getTag() == 2)
{
// rider out and it will satrt from start point
}
}
return false;
}
回答1:
Try Like this:-
bool wall::HandleBeginContact(b2Fixture *fixtureA,b2Fixture *fixtureB)
{
b2Body *bodyA = fixtureA->GetBody();
b2Body *bodyB = fixtureB->GetBody();
if(CartBody == bodyA || CartBody == bodyB )
{
CCLog("am collided correctly");
}
return false;
}
来源:https://stackoverflow.com/questions/24649355/cocos2dx-box2d-b2body-getuserdata-always-returns-null