cocos2D和Box2D:如何获得精确触摸的精灵?

时间:2012-08-17 06:35:15

标签: iphone cocos2d-iphone box2d

我试图移动精灵触摸移动。但是当我有两个精灵时,我正准备接触两个精灵。这就是为什么精灵没有正常运动。

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
{

if (_mouseJoint != NULL) return;

    UITouch *myTouch = [touches anyObject];
    CGPoint location = [myTouch locationInView:[myTouch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

    for(int i=0;i<[mutArrFixtures count];i++)
    {
        b2Fixture *fixture;
        [[mutArrFixtures objectAtIndex:i] getValue:&fixture];

        if (fixture->TestPoint(locationWorld)){

            for(int j=0; j<[mutArrPaddleBody count]; j++)
            {
                b2Body *body;
                [[mutArrPaddleBody objectAtIndex:j] getValue:&body];
                b2MouseJointDef md;
                if(body == fixture->GetBody())
                {
                    md.bodyA = _groundBody;
                    md.bodyB = body;
                    md.target = locationWorld;
                    md.collideConnected = true;
                    md.maxForce = 1000.0f * body->GetMass();

                    _mouseJoint = (b2MouseJoint *)_world->CreateJoint(&md);
                    body->SetAwake(true);
                }
            }
        }
    }
}

我有b2Fixture mutArrFixtures的数组以及b2body的数组mutArrPaddleBody。但是如果我触摸第二个精灵,我会触及第一个精灵和第二个精灵......两个精灵位置相同...

1 个答案:

答案 0 :(得分:1)

在触控功能中,检查精灵的标签。如果这是你的右精灵然后移动。给我看一些你用于触摸移动的代码。

.......

将这些代码替换为下一个

            b2Body *body;
            [[mutArrPaddleBody objectAtIndex:j] getValue:&body];
            b2MouseJointDef md;
            if(body == fixture->GetBody())

b2Body* body = fixture->GetBody();

CCSprite *sprite = (CCSprite*)body->GetUserData();

if( sprite && sprite.tag == kTagHero) 
{

}

确保为你移动的精灵添加了标签kTagHero。

...

enum gameTag {
  kTagHero = 1001
};

并指定sprite.tag = kTagHero ......