user1028028
user1028028

Reputation: 6433

Smooth motion of a SKSpriteNode on a random path

I am making a small SpriteKit game. I want the "enemies" in this game to move on random paths around the player (which is static).

If I just select a random point on the screen and animate a motion to there and then repeat (e.g.: every 2 seconds), this will give a very jagged feel to the motion.

How do I make this random motion to be very smooth (e.g.: if the enemy decides to turn around it will be on a smooth U turn path not a jagged sharp angle).

PS: The enemies must avoid both the player and each other.

Upvotes: 5

Views: 4294

Answers (2)

Ahmet Hayrullahoglu
Ahmet Hayrullahoglu

Reputation: 960

If you want to generate random path, I highly suggest you to use "CGPathAddCurveToPoint", it is simple to understand and easy to use

Go to title 2. Add & Move Enemies

http://code.tutsplus.com/tutorials/build-an-airplane-game-with-sprite-kit-enemies-emitters--mobile-19916

It is coded by Jorge Costa and Orlando Pereira

Upvotes: 0

Rafał Sroka
Rafał Sroka

Reputation: 40030

You can create an SKAction with a CGPathRef that the node should follow.

Here is an example how to make a node make circles:

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];

You can also create a random UIBezierPath to define more sophisticated paths and make your objects follow them.

For example:

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));
}

You make a node follow the path using an SKAction and when the action completes (node is at the end of the path), you calculate a new path.

This should point you to the right direction.

Upvotes: 6

Related Questions