Hiren
Hiren

Reputation: 112

cocos2D and Box2D : How to get exact touched sprite?

I am trying to move sprite on touch moved. but when two sprites is there i am geting touch of two sprites. that's why sprites are not moving properly.

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

i have an array of b2Fixture mutArrFixtures and also an array mutArrPaddleBody of b2body. but in this if i touch on second sprite i get touch on first sprite and second sprite.. two sprites positions are same...

Upvotes: 1

Views: 757

Answers (1)

Guru
Guru

Reputation: 22042

In touch function, check tag of the sprite. If that is ur right sprite then move. Show me some code that u used for touch movement.

.......

Replace these code with next one

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

with

b2Body* body = fixture->GetBody();

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

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

}

Make sure u added tag kTagHero for ur moving sprite.

....

enum gameTag {
  kTagHero = 1001
};

and assign sprite.tag = kTagHero ......

Upvotes: 1

Related Questions