如何使用touch在cocos2d中上下移动精灵

时间:2012-06-18 01:04:48

标签: ios cocos2d-iphone

我正试图上下移动我的精灵。这是我的代码。我不知道这个问题。可能是内容大小搞砸了。精灵只是不断消失。

    CGSize winSize = [[CCDirector sharedDirector] winSize];
    player = [CCSprite spriteWithFile:@"Player.png" 
                                           rect:CGRectMake(0, 0, 27, 40)];
    player.position = ccp(player.contentSize.width/2, winSize.height/2);
        [self addChild:player z:1]; 

    (void) registerWithTouchDispatcher
    {
        [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self 
                                                 priority:0 swallowsTouches:YES];
    }

    -(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
    {
        return YES;
    }

    -(void)setPlayerPosition:(CGPoint)position {
        player.position = position;
    }

    -(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event  {
        CGPoint touchLocation = [touch locationInView: [touch view]];       
        touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];

        CGPoint playerPos = player.position;
        CGPoint diff = ccpSub(touchLocation, playerPos);
        if (abs(diff.x) > abs(diff.y)) {
            if (diff.x > 0) {
                playerPos.x += contentSize_.width;
            } else {
                playerPos.x -= contentSize_.width; 
            }    
        } else {
            if (diff.y > 0) {
                playerPos.y += contentSize_.height;
            } else {
                playerPos.y -= contentSize_.height;
            }
        }

        if (playerPos.x <= (contentSize_.width *contentSize_.width) &&
            playerPos.y <= (contentSize_.height * contentSize_.height) &&
            playerPos.y >= 0 &&
            playerPos.x >= 0 ) 
        {
            [self setPlayerPosition:playerPos];
        }
    }

0 个答案:

没有答案