How to move spirte by touch android app cocos2d

173 views Asked by At

i want to move a sprite by touching on screen, i want the sprite to move to the place which I touched. i have implemented a code but it crashes, i want to move a sprite by touching the screen to that point but my app crashes.

public class GameLayer extends CCLayer {

static final int kTagSprite = 1;
public static CCScene scene()
{

    CCScene scene = CCScene.node();
    CCLayer layer = new GameLayer();

    scene.addChild(layer);


    return scene;
}

protected  GameLayer()
{
    this.setIsTouchEnabled(true);

    CCSprite player2 = CCSprite.sprite("Yellow.png") ;
    player2.setPosition(CGPoint.ccp(150 , 150));

    addChild(player2 , kTagSprite );

}

@Override
public boolean ccTouchesBegan(MotionEvent event) {
    //create point takes coordinates of touch
    CGPoint convertedLocation = CCDirector.sharedDirector()
        .convertToGL(CGPoint.make(event.getX(), event.getY()));



    CCNode s = getChild(kTagSprite);
    s.stopAllActions();
    s.runAction(CCMoveTo.action(1.0f, convertedLocation));


    return CCTouchDispatcher.kEventHandled;
    }

}
2

There are 2 answers

0
Rama On

you have to check the condition:

**

CCNode s = this.getChildByTag(kTagSprite);
 if(s!= null && s.isRunning()){
   s.stopAllActions();
}

**

It will work.Try this.If not place the log

0
StevoF On

You've used kTagSprite as wrong argument in addchild function. You have used addchild function as:

addchild(spriteParameter, z-orderParameter); 

You need to use addchild as:

addchild(spriteParameter, z-orderParameter, spriteTagParameter);

So you need to replace:

addChild(player2, kTagSprite );

with:

addChild(player2, 1, kTagSprite );