Reputation: 6433
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
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
It is coded by Jorge Costa and Orlando Pereira
Upvotes: 0
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