SKSpriteNode在随机路径上的平滑运动

use*_*028 4 random objective-c ios sprite-kit

我正在做一个小SpriteKit游戏.我想让这个游戏中的"敌人"在玩家周围的随机路径上移动(这是静态的).

如果我只是在屏幕上选择一个随机点并将动画设置为动画然后重复(例如:每2秒),这将给动作带来非常锯齿状的感觉.

如何使这个随机运动非常平滑(例如:如果敌人决定转身,它将在平滑的U转弯路径上而不是锯齿状的锐角).

PS:敌人必须避免玩家和对方.

Raf*_*fAl 5

您可以创建一个SKActionCGPathRef该节点应该遵循.

以下是如何使节点创建圆圈的示例:

SKSpriteNode *myNode = ...

CGPathRef circlePath = CGPathCreateWithEllipseInRect(CGRectMake(0, 
                                                                0, 
                                                              400, 
                                                             400), NULL);
SKAction *followTrack = [SKAction followPath:circle 
                                    asOffset:NO 
                                orientToPath:YES 
                                    duration:1.0];

SKAction *forever = [SKAction repeatActionForever:followTrack];
[myNode runAction:forever];
Run Code Online (Sandbox Code Playgroud)

您还可以创建随机UIBezierPath来定义更复杂的路径并使对象跟随它们.

例如:

UIBezierPath *randomPath = [UIBezierPath bezierPath];
[randomPath moveToPoint:RandomPoint(bounds)];
[randomPath addCurveToPoint:RandomPoint(YourBounds)
              controlPoint1:RandomPoint(YourBounds)
              controlPoint2:RandomPoint(YourBounds)];

CGPoint RandomPoint(CGRect bounds)
{
    return CGPointMake(CGRectGetMinX(bounds) + arc4random() % (int)CGRectGetWidth(bounds),
                       CGRectGetMinY(bounds) + arc4random() % (int)CGRectGetHeight(bounds));
}
Run Code Online (Sandbox Code Playgroud)

您使用SKAction使节点遵循路径,并且当操作完成时(节点位于路径的末尾),您计算新路径.

这应该指向正确的方向.