【问题标题】:Cocos2D - Drag Sprite without Touch!Cocos2D - 无需触摸即可拖动 Sprite!
【发布时间】:2011-07-13 19:59:46
【问题描述】:

我是 cocos2d 的新手,正在阅读很多教程 我想做的是触摸屏幕,让精灵跟随我的触摸。 松开触摸时,精灵停止 当触摸远离精灵时,即使我的手指连续移动,精灵也应该开始移动。 我该怎么做?

我尝试不同的方式:

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    isMoving = YES;
    [self schedule:@selector(moveSprite:)];
    return YES;
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    isMoving = NO;
    [self unschedule:@selector(moveSprite:)];
}

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

-(void)moveSprite:(ccTime) dt {

    CGPoint moveVector = ccpSub(touchLocation, mySprite.position);

    float distanceToMove = ccpLength(moveVector);
    float velo = 480.0/3.0;
    float moveDuration = distanceToMove / velo;

    self.moveAction = [CCSequence actions:
                       [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                       nil
                       ];

    [mySprite runAction:_moveAction];   

}

或再次使用:

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {

    CGPoint touchLocation = [recognizer locationInView:recognizer.view];
    touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
    touchLocation = [self convertToNodeSpace:touchLocation];                

    moveAction = [CCSequence actions:
                       [CCMoveTo actionWithDuration:2.0f position:touchLocation],
                       nil
                       ];

    [mySprite runAction:moveAction];
}

或者简单的

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

    [_mySprite stopAction:_moveAction];
    _moveAction = [CCMoveTo actionWithDuration:1 position:touchLocation];
    [_mySprite runAction:_moveAction];
}

有人可以帮忙吗? 非常感谢!

【问题讨论】:

  • 第三个在我看来应该可以工作。它实际上在做什么?

标签: iphone xcode cocos2d-iphone touch sprite


【解决方案1】:

第三个效果不好,即使我检查'moveDuration'并将其放入动作中,动作也不流畅

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多