如何让精灵跟踪?

时间:2012-05-18 19:43:32

标签: iphone ios cocos2d-iphone touches trail

我正在制作一个游戏,其中玩家绘制一条线,然后一个精灵应该跟随并在其上运行。我有一个可变数组,也有一个效果很好的绘制方法。但是我在找出移动精灵的方法时遇到了麻烦。我尝试了不同的方法,但我无法让迭代器工作。

它应该通过遍历数组来工作。其中填充了先前存储的CGPoint位置。我尝试在ccTouchedEnded中移动精灵,但它突出显示[toucharray objectAtIndex:0]并说“将'id'传递给不兼容类型的参数'CGPoint(又名'struct CGPoint')”

   -(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  { 
    //remove objects each time the player makes a new path
    [toucharray removeAllObjects];
}

-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event  {    
    UITouch *touch = [ touches anyObject];
    CGPoint new_location = [touch locationInView: [touch view]];
    new_location = [[CCDirector sharedDirector] convertToGL:new_location];

    CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
    oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
    oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];

    // add touches to the touch array 
   [toucharray addObject:NSStringFromCGPoint(new_location)];
    [toucharray addObject:NSStringFromCGPoint(oldTouchLocation)];

}

-(void)draw
{
    glEnable(GL_LINE_SMOOTH);

    for(int i = 0; i < [toucharray count]; i+=2)
    {
        CGPoint start = CGPointFromString([toucharray objectAtIndex:i]);
        CGPoint end = CGPointFromString([toucharray objectAtIndex:i+1]);
        ccDrawLine(start, end);
    }
}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

  // here is the line I can't get to work to move the sprite

 _sprite.position = ccpAdd(ccpMult([toucharray objectAtIndex:0], progress),         ccpMult([toucharray objectAtIndex:0+1], 1-progress));

}

2 个答案:

答案 0 :(得分:2)

我之前做过这个,通过(你到目前为止)创建一个数组 我的屏幕上有多个精灵,所以我也有1个定义“Touched sprite”

ontouchstart空数组并添加第一个点(起始点)+将TouchedSprite设置为最接近起点的Sprite) ontouchmove将数组添加到数组中 ontouchend(通过动作在精灵上运行数组(稍后再回来)

我得到的一些问题,(1)我一次只能控制1个精灵,(2)绘制的线有太多的点。

第1号解决方案: 创建精灵的子类Object并创建这样的精灵。在该对象中创建一个数组(使用@property和@synthesize可以访问它),这将允许您放置绘制的路径点。还创建一个名为“runPathAction”的公共方法。 所以onTouchStart你清理数组并设置选定的spriteObject。 OnTouchMove添加项目,OntouchEnd将所选spriteObject的数组设置为本地数组,然后运行“runPathAction”方法。 (你可以将它传递给方法,但我喜欢这样做,以防万一我想访问数组)

第2号解决方案: 我发现绘制线条会为很多点创建方法。因此,我创建了一个名为“CanDraw”的布尔运算符和一个时间间隔为0.1的计划(您可以使用它)到一个将canDraw设置为YES的方法。然后在onTouchMove中检查“canDraw == YES”,添加点并设置canDraw = NO;

这样,您将有0.1秒的间隔来添加点数。不要忘记删除onTouchEnd !!!的计划表。


现在如何运行动作。 您需要稳定的速度,因此您需要设置速度变量。 遍历点阵列并计算每个点之间的距离以创建总距离。 (PS不要忘记第一个品脱是从数组中的CurrentLocation到Point0) 当你有总距离时,你可以计算出你应该在每一步的行动中设置多少延迟时间。 (如果你不这样做,你不知道延迟时间,如果你修复了,你会得到奇怪的动作)。

创建方法, 检查数组的“计数”。如果count = 0则返回; (完成!!!做清理或其他) 否则运行一个actionsequence,最后调用自己。 (计数检查将处理“休息”。 抓取数组CGPoint的1项p =(objectAtIndex:0);并从数组中删除该项(removeAtIndex:0)。 用延迟时间运行动作然后你就去了!

答案 1 :(得分:1)

在数组或列表中记录路径的位置并迭代它以沿着轨迹移动精灵。我在一个游戏中做到了这一点,我在玩家后面创建了一个粒子轨迹。我使用了一个20号数组,并在一个时间间隔内迭代,使用我的角色的位置更新迭代器位置的数组,然后将粒子效果移动到迭代器加1处数组中存储的位置。 / p>

你需要使用起始位置对数组进行种子处理,这样你就不会有空值,当你在数组的末尾时,你需要一个特殊的例子,因为你不想从超出范围的位置读取,而不是从0位置读取代码。