2013-07-01 2 views
0

Вот что я пробовал снарядить, чтобы сделать какое-то действие при нажатии на пистолет (спрайт) , но при касании спрайта canon1 «снаряды» не выходят , пожалуйста, если кто-нибудь знает, что это мне поможет.Как заставить спрайт отреагировать на касание на него в cocos2d android

@Override 
public boolean ccTouchesBegan(MotionEvent event)  
{ 


    // Choose one of the touches to work with 
// CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY())); 


    if(CGRect.containsPoint((canon2.getBoundingBox()), location)){ 

    // Set up initial location of projectile 
    CGSize winSize = CCDirector.sharedDirector().displaySize(); 
    _nextProjectile = CCSprite.sprite("fireball50.png"); 
    System.out.println("projectile working"); 
    //_nextProjectile.setPosition(20, winSize.height/2.0f); 
    _nextProjectile.setPosition(CGPoint.ccp(65, 120)); 

    // Determine offset of location to projectile 
    int offX = (int)(location.x - _nextProjectile.getPosition().x); 
    int offY = (int)(location.y - _nextProjectile.getPosition().y); 

    // Bail out if we are shooting down or backwards 
    if (offX <= 0)  
     return true; 

    _nextProjectile.setTag(3); 

    // Determine where we wish to shoot the projectile to 
    int realX = (int)(winSize.width + (_nextProjectile.getContentSize().width/2.0f)); 
    float ratio = (float)offY/(float)offX; 
    int realY = (int)((realX * ratio) + _nextProjectile.getPosition().y); 
    CGPoint realDest = CGPoint.ccp(realX, realY); 

    float velocity = 480.0f/1.0f; // 480 pixels/1 sec 
    float realMoveDuration = length/velocity; 


     // Move projectile to actual endpoint 
    _nextProjectile.runAction(CCSequence.actions(
      CCMoveTo.action(realMoveDuration, realDest), 
      CCCallFuncN.action(this, "spriteMoveFinished"))); 

}

+0

где вы нашли такую ​​декларацию 'метода ccTouchesBegan' ? обычно он ничего не возвращает ('void') и получает множество касаний и событий в качестве параметров. убедитесь, что вы перегрузили необходимый метод. – Morion

+0

он работал отлично, прежде чем давать эту строку, если (CGRect.containsPoint ((canon2.getBoundingBox()), местоположение)), при касании какой-либо части экранного снаряда выстрелил, но после выдачи строки выше ничего не получилось @Morion –

+0

какая часть не работает в вашем коде? Распечатывается ли журнал? И как вы получаете свое касание? –

ответ

1

первым установить контакт будет включить использование

 this.setIsTouchEnabled(true); 

затем измените функцию

public boolean ccTouchesBegan(MotionEvent event) 
{ 
    CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(event.getX(), event.getY())); 

    // Set up initial location of projectile 
    CGSize winSize = CCDirector.sharedDirector().displaySize(); 
    _nextProjectile = CCSprite.sprite("fireball50.png"); 

    // _nextProjectile.setPosition(20, winSize.height/2.0f); 
    _nextProjectile.setPosition(CGPoint.ccp(65, 120)); 


    for (CCSprite target : targets) 
     { 

      if (CGRect.containsPoint((target.getBoundingBox()), location)) 
       { 

        // Determine offset of location to projectile 
        int offX = (int) (location.x - _nextProjectile.getPosition().x); 
        int offY = (int) (location.y - _nextProjectile.getPosition().y); 

        // Bail out if we are shooting down or backwards 

        _nextProjectile.setTag(3); 
        // Determine where we wish to shoot the projectile 
        // to 
        int realX = (int) (winSize.width + (_nextProjectile.getContentSize().width/2.0f)); 
        float ratio = (float) offY/(float) offX; 
        int realY = (int) ((realX * ratio) + _nextProjectile.getPosition().y); 
        CGPoint realDest = CGPoint.ccp(realX, realY); 

        // Determine the length of how far we're shooting 
        int offRealX = (int) (realX - _nextProjectile.getPosition().x); 
        int offRealY = (int) (realY - _nextProjectile.getPosition().y); 
        float length = FloatMath.sqrt((offRealX * offRealX) + (offRealY * offRealY)); 
        float velocity = 480.0f/1.0f; // 480 pixels/1 
                // sec 
        float realMoveDuration = length/velocity; 
        System.out.println(" - t tag!!!!!!!!!!!!!!!!!!!!! - "); 
        _nextProjectile.runAction(CCSequence.actions(CCMoveTo.action(realMoveDuration, realDest), 
          CCCallFuncN.action(this, "spriteMoveFinished"))); 
        double angleRadians = Math.atan((double) offRealY/(double) offRealX); 
        double angleDegrees = Math.toDegrees(angleRadians); 
        double cocosAngle = -1 * angleDegrees; 
        double rotationSpeed = 0.5/Math.PI; 
        double rotationDuration = Math.abs(angleRadians * rotationSpeed); 

        target.runAction(CCSequence.actions(
          CCRotateTo.action((float) rotationDuration, (float) cocosAngle), 
          CCCallFunc.action(this, "finishShoot"))); 
        break; 
       } 
     } 


    return true; 
}