Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Todd Baker
17,207 PointsConstant movement of a SKSpriteNode
I am trying to create a program where an SKSpriteNode of a spaceship is in constant motion from the left to right hand side of the screen. I currently have a class set up as follows: @implementation TBShipNode
-
(instancetype) shipAtPosition:(CGPoint)position{ TBShipNode *ship = [self spriteNodeWithImageNamed:@"ship-small_01"]; ship.position = position;
return ship; }
(void) shipMovement:(CGPoint)position{ SKAction *moveShipRight = [SKAction moveTo:CGPointMake(325, 50) duration:.5]; SKAction *moveShipLeft = [SKAction moveTo:CGPointMake(0, 50) duration:.5]; SKAction *moveSequence = [SKAction sequence:@[moveShipLeft,moveShipRight]]; [self runAction:moveSequence]; }
@end
It works to move the ship from left to right once, but how do I make it continuous? Any tips?
1 Answer
Stone Preston
42,016 Pointsuse the repeatActionForever class method of SKAction.
@implementation TBShipNode
+ (instancetype) shipAtPosition:(CGPoint)position{
TBShipNode *ship = [self spriteNodeWithImageNamed:@"ship-small_01"];
ship.position = position;
return ship;
}
- (void) shipMovement:(CGPoint)position{
SKAction *moveShipRight = [SKAction moveTo:CGPointMake(325, 50) duration:.5];
SKAction *moveShipLeft = [SKAction moveTo:CGPointMake(0, 50) duration:.5];
SKAction *moveSequence = [SKAction sequence:@[moveShipLeft,moveShipRight]];
//repeat the sequence forever
SKAction *repeat = [SKAction repeatActionForever:moveSequence];
[self runAction:repeat];
}
Todd Baker
17,207 PointsTodd Baker
17,207 PointsThanks! That helped a lot.