如何使精灵沿着贝塞尔曲线移动?

8
我对Objective-C和Sprite Kit比较新,但我已经从事游戏开发一段时间了。我目前正在开发一款2D游戏,其中有敌舰从右到左移动屏幕。我一直在跟随不同部分的教程并在必要时添加内容。我找到了一个教程,其中游戏中的敌人遵循贝塞尔曲线路径,我已经成功将其实现在我的游戏中,但是由于我是新手,我并不完全理解它们,而且算法使我的精灵从上到下移动,但我需要它们从左到右移动。
我已经包含了用于向我的精灵添加贝塞尔曲线的代码段,您有什么建议可以让它们从右到左移动而不是从上到下?
CGMutablePathRef cgpath = CGPathCreateMutable();

        float xStart = [self getRandomNumberBetween:0+asteroid.size.width to:self.frame.size.width-asteroid.size.width];
        float xEnd = [self getRandomNumberBetween:0+asteroid.size.width to:self.frame.size.width-asteroid.size.width];
        float cp1X =[self getRandomNumberBetween:0+asteroid.size.width to:self.frame.size.width-asteroid.size.width];
        float cp1y = [self getRandomNumberBetween:0+asteroid.size.width to:self.frame.size.width-asteroid.size.height];
        float cp2x = [self getRandomNumberBetween:0+asteroid.size.width to:self.frame.size.width-asteroid.size.width];
        float cp2Y = [self getRandomNumberBetween:0 to:cp1y];

        CGPoint s = CGPointMake(xStart, 1024.0);
        CGPoint e = CGPointMake(xEnd, -100);
        CGPoint cp1 = CGPointMake(cp1X, cp1y);
        CGPoint cp2 = CGPointMake(cp2x, cp2Y);
        CGPathMoveToPoint(cgpath, NULL, s.x, s.y);
        CGPathAddCurveToPoint(cgpath, NULL, cp1.x, cp1.y, cp2.x, cp2.y, e.x, e.y);

        SKAction *enemyCurve = [SKAction followPath:cgpath asOffset:NO orientToPath:YES duration:5];

  CGPoint location = CGPointMake(-self.frame.size.width-asteroid.size.width, randY);

        SKAction *moveAction = [SKAction moveTo:location duration:randDuration];
        SKAction *doneAction = [SKAction runBlock:(dispatch_block_t)^(){

            asteroid.hidden = YES;
        }];

        SKAction *moveAsteroidActionWithDone = [SKAction sequence:@[enemyCurve,moveAction, doneAction]];

感谢任何帮助和建议。

1个回答

9
贝塞尔曲线用于在两个点之间生成平滑的曲线。要将路径从左到右移动,请选择左侧的起始点并选择右侧的结束点。两个控制点确定路径从左到右的形状。在以下代码中,变化startpointendpoint将控制贝塞尔曲线的起点和终点。变化control points会改变曲线的形状。您可以通过附带的GIF看到这一点。
CGMutablePathRef cgpath = CGPathCreateMutable();

CGPoint startingPoint = CGPointMake(50, 100);

CGPoint controlPoint1 = CGPointMake(160, 250);
CGPoint controlPoint2 = CGPointMake(200, 140);

CGPoint endingPoint = CGPointMake(303, 100);


CGPathMoveToPoint(cgpath, NULL, startingPoint.x, startingPoint.y);
CGPathAddCurveToPoint(cgpath, NULL, controlPoint1.x, controlPoint1.y,
                      controlPoint2.x, controlPoint2.y,
                      endingPoint.x, endingPoint.y);


SKAction *enemyCurve = [SKAction followPath:cgpath asOffset:NO orientToPath:YES duration:5];

[enemy runAction:[SKAction sequence:@[[SKAction waitForDuration:1],enemyCurve]]];

图片描述

P0P3 是起点和终点,P1P2 是控制点。

访问此页面以更多地了解贝塞尔曲线。 http://www.jasondavies.com/animated-bezier/


1
这正是我一直在寻找的,感谢您清晰的解释,我已经成功地将其实现到我的游戏中并且它运行良好。 - Tony_89
你知道怎么让精灵面向它移动的方向吗?我设置了 orientToPath: YES,但它只朝曲线的最终点朝向,你有什么建议可以让它指向它正在移动的方向吗?再次感谢。 - Tony_89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接