我正在制作一个游戏,玩家在游戏中画一条线,然后跟随精灵并在其上奔跑。我有一个可变的数组,也很好地使用了draw方法。但我在想办法移动精灵时遇到了麻烦。我尝试了不同的方法,但是无法使迭代器正常工作。

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

}

最佳答案

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

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

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

解决方案1:
创建一个精灵的子类对象,并像这样创建您的精灵。在该对象内创建一个数组(使其可以使用@property和@synthesize进行访问),该数组将允许您放置绘制的路径点。还要创建一个名为“runPathAction”的 public 方法。
因此,onTouchStart可以清理Array并设置选定的spriteObject。添加OnTouchMove项后,OntouchEnd将所选spriteObject的数组设置为本地数组,然后运行“runPathAction”方法。 (您可能已经将它传递给了方法,但是我喜欢这样做,以防万一我想访问数组)

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

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

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

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

10-08 17:56