我使用cocos2d制作了第一个应用程序,所以我在这里很新

我的第一个问题:

我不会让物体(船)跟随我的手指。

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint location = [self convertTouchToNodeSpace: touch];
    NSLog(@"location X: %f", location.x);
    NSLog(@"location Y: %f", location.y);


    if(startGameButtonIsPressed == YES) {
        [boat runAction: [CCMoveTo actionWithDuration:1 position:location]];
    }
}


它的确会跟随,但不是流动的。如果我快速移动手指,它就会停止,只有停止时才跟随。

第二个问题

如何计算2点之间的距离。

CGPoint currentLocation = ccp(boat.position.x, boat.position.y);
float distanceApart = ccpDistance(currentLocation, location);


问题,currentLocation在每次具有其他值的每个点上都不恒定。

也许因为我有滚动背景?

最佳答案

您每秒调用多次[boat runAction: [CCMoveTo actionWithDuration:1 position:location]];,这将导致多个CCMoveTo操作同时运行。这不是设计cocos2d的Action工具的方式。

如果希望船以您定义的较慢速度跟随触摸,则不能将多个CCMoveTo操作排队以响应ccTouchMoved:

而是将UITouch对象(或NSValueCGPoint)推到NSMutableArray上。然后定义一个回调函数,以使您的船在每次CCMoveTo完成后继续前进。

示例代码:

//...defined elsewhere, e.g. your header file:
    #define kBoatMoveTag 123

    NSMutableArray *touchQueue; //treat the array like a queue.
                                //don't forget to alloc it before using.


-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint location = [self convertTouchToNodeSpace: touch];
    NSLog(@"location X: %f", location.x);
    NSLog(@"location Y: %f", location.y);

    [touchQueue insertObject:[NSValue valueWithCGPoint:location] atIndex:0];
    [self continueBoatMovement];
}

-(void)continueBoatMovement {
    //if no queued point, or boat is already moving...
    if(touchQueue.count < 1 || [boat getActionByTag:kBoatMoveTag]) {
        return; //dont do anything
    }

    NSValue valueOfPt = [touchQueue lastObject];
    [touchQueue removeLastObject];
    CGPoint newPt = [valueOfPt CGPointValue];
    float distance = ccpDistance(boat.position, newPt);
    float duration = distance / boatSpeed; //you must define boatSpeed somewhere

    CCMoveTo *move = [CCMoveTo actionWithDuration:duration position:newPt];

    CCSequence *moveSeq = [CCSequence actionOne:move two:[CCCallFunc actionWithTarget:self selector:@selector(continueBoatMovement)]];
    moveSeq.tag = kBoatMoveTag;
    [boat runAction:moveSeq];
}

关于ios - cocos2d使对象跟随触摸/手指,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11726218/

10-09 02:34