user1042757
user1042757

Reputation: 121

cocos2d android touching a sprite

I'm new to cocos2d and I was wondering how do I write a code in java that checks to see if I've touched a sprite I've already tried something like this..

@Override
public boolean ccTouchesEnded(MotionEvent event)
{

    CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY()));

    if ((location.x == zom.getPosition().x) && (location.y == zom.getPosition().y))
    {
    CCSprite projectile = CCSprite.sprite("bullet.png");
    projectile.setPosition(CGPoint.ccp(player.getPosition().x,player.getPosition().y));
    addChild(projectile);
    float length = (float)Math.sqrt((100 * 100) + (100 * 100));
    float velocity = 100.0f / 1.0f; 
    float realMoveDuration = length / velocity;
    projectile.runAction(CCSequence.actions(
            CCMoveTo.action(realMoveDuration, CGPoint.ccp(location.x, location.y)),
            CCCallFuncN.action(this, "spriteMoveFinished")));
      if ((projectile.getPosition().x == location.x) && ( projectile.getPosition().y == location.y))
      {
          removeChild(projectile, true);
      }
    }

Upvotes: 0

Views: 1753

Answers (3)

Bebin T.N
Bebin T.N

Reputation: 2649

I hope this will help you. I am using this way to handle touch event for particular spite.

public boolean ccTouchesEnded(MotionEvent event) {
        CGPoint location = CCDirector.sharedDirector().convertToGL(
                CGPoint.ccp(event.getX(), event.getY()));
        if (CGRect.containsPoint((newGame1.getBoundingBox()), location)) {

            newGame();

        }

        return super.ccTouchesEnded(event);
    }

please add this to constructor

this.setIsTouchEnabled(true);

Upvotes: 1

D.W.
D.W.

Reputation: 1

While I am not a cocos2d master, it looks like the logic is a bit off in checking your code. You want to check to see if the touch point is in the sprites current area (i.e. is ((location.x >= sprite.start.x && location.x <= sprite.width) && ((location.y >= sprite.start.y && location.y <= sprite.height).

I think a better way is to extend the sprite class and include a function to check and see if a point is in the sprite area (float isInSpriteArea(CGPoint point)). That way you can just pass a point to a sprite and it can tell you if it is in this case touched.

Upvotes: 0

Waqas
Waqas

Reputation: 999

There is a very best solution for that. Use:

sprite.getBoundingBox.contains(x,y);

where x and y are positions of touched location.

Upvotes: 1

Related Questions