Search code examples
iphoneioscocos2d-iphoneccsprite

I want to move sprite body when touch point detect


I want to move sprite body when i touch screen but it cant happen...

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
    for(b2Body *b=world->GetBodyList();b;b=b->GetNext())
    {
    CGPoint location=[touch locationInView:[touch view]];
        location=[[CCDirector sharedDirector]convertToGL:location];
         b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);


        if(b->GetUserData()!=NULL)
        {
        CCSprite *sprite =(CCSprite *)b->GetUserData();

            b->SetTransform(b2Vec2(location.x, location.y), 0);
            id action = [CCMoveTo actionWithDuration:0.4 position:CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO)];
             [sprite runAction:action];
        }
     }
}

please help me... thanks


Solution

  • Please try the below code it would work for you.

    - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
    {       
        for( UITouch *touch in touches ) {
            CGPoint location = [touch locationInView: [touch view]];
    
            location = [[CCDirector sharedDirector] convertToGL: location];
            for(b2Body *b=world->GetBodyList();b;b=b->GetNext())
            {
                if(b->GetUserData()!=NULL)
                {
                    CCSprite *sprite =(CCSprite *)b->GetUserData();
                    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
                    b->SetTransform(b2Vec2(locationWorld.x, locationWorld.y), 0);
                    id action = [CCMoveTo actionWithDuration:0.4 position:CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO)];
                    [sprite runAction:action];
    
                }
            }
    
        }
    }
    

    The sprite with the body moves to a location where the touch is Ended.