Cocos2d机器人触摸精灵



我是cocos2d的新手,我想知道如何在java中编写代码来检查我是否已经触摸了一个精灵,我已经尝试过这样的东西。

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

有一个非常好的解决方案。用途:

sprite.getBoundingBox.contains(x,y);

,其中x和y为触摸位置。

我希望这对你有帮助。

我用这种方式来处理触摸事件。
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);
    }

请将此添加到构造函数

this.setIsTouchEnabled(true);

虽然我不是cocos2d大师,但看起来在检查代码时逻辑有点偏离。你需要检查触点是否在精灵的当前区域(即((location.x >= sprite.start.x && location.x <= sprite.width) && ((location.y >= sprite.start.y && location.y <= sprite.height))。

我认为更好的方法是扩展精灵类,并包含一个函数来检查和查看一个点是否在精灵区域(float isInSpriteArea(CGPoint point))。这样你就可以将一个点传递给精灵,它会告诉你在这种情况下它是否被触摸。

最新更新