用文字绘制箭头曲线(Objective-c cocos2D)

时间:2014-11-06 21:35:07

标签: cocos2d-iphone curve words fractals

我试图用Fibonacci-esque字词绘制箭头曲线。我可能会使用方法调用而不是稍后构建到字符串上,但是现在我想保留字符串。

// create string. Initially set to "A"
NSMutableString *s1 = [[NSMutableString alloc] init];

[s1 setString:@"A"];

// loop through and replace A and B with the following strings. Toned down iterations to 5 here

for(int i=0; i<5; ++i){

    [s1 replaceOccurrencesOfString:@"A"
                  withString:@"+B-A-B+"
                      options:NSLiteralSearch
                             range:NSMakeRange(0, s1.length)];


    [s1 replaceOccurrencesOfString:@"B"
                          withString:@"-A+B+A-"
                  options:NSLiteralSearch
                         range:NSMakeRange(0, s1.length)];
}

// set line color, thickness
ccDrawColor4F(0.8, 1.0, 0.76, 1.0);
glLineWidth(1.0f);

float angle = 0;

float travelDist = 1; // distance in pixels the line is drawn. Can be changed to whatever

CGPoint p = CGPointMake(300,100);

for(int i = 0; i < [s1 length]; i++){

    if([[NSString stringWithFormat:@"%c",[s1 characterAtIndex:i]] isEqualToString:@"+"]){  // turn right

        angle += 60;

    }else if([[NSString stringWithFormat:@"%c",[s1 characterAtIndex:i]] isEqualToString:@"-"]){ // turn left

        angle -= 60;

    }else{ // any other character, draw line

            float cosAngle = cosf(CC_DEGREES_TO_RADIANS(angle));

        float newDist = travelDist * cosAngle;

        float sinAngle = sinf(CC_DEGREES_TO_RADIANS(angle));

        float newDist2 = travelDist *sinAngle;

        ccDrawLine( ccp(p.x, p.y), ccp(p.x + newDist, p.y + newDist2) );

        p = CGPointMake(p.x + newDist, p.y + newDist2);

    }



}

我已经在几个网站上阅读了有关箭头曲线及其必须遵循的规则的信息。看起来我应该做正确的事,但事实并非如此。我得到了代表Sierpinski三角形的东西,但没有一个正确的箭头曲线。

enter image description here

你可能不必知道Objective-c / Cocos2d来回答这个问题,因为我可能只是做了一些逻辑错误的事情。

1 个答案:

答案 0 :(得分:0)

我需要根据当前字符串创建一个新的临时字符串,并一次浏览一个字符,并在每次迭代结束时使字符串成为临时字符串:

NSMutableString *s1 = [[NSMutableString alloc] init];

[s1 setString:@"A"];

NSMutableString *sTemp = [[NSMutableString alloc] init];

[sTemp setString:@""];


for(int i=0; i<6; ++i){

    for(int j = 0; j < [s1 length]; j++){


        unichar character = [s1 characterAtIndex:j];

        if(character == 'A'){

            [sTemp appendString:@"B-A-B"];

        }
        else if(character == 'B'){

            [sTemp appendString:@"A+B+A"];

        }else{

            [sTemp appendString:[NSString stringWithFormat:@"%C",character]];

        }

    }

    [s1 setString:sTemp];

    [sTemp setString:@""];

}