我正在尝试使用Apple的SpriteKit进行侧滚动游戏.当想要制作无休止的滚动背景时,我遇到了这个
answer.
在实施解决方案后,它似乎确实有效,尽管它显着降低了我的FPS.这可能是由于在每一帧上重新计算图像位置的事实.
我觉得如果我可以使用一个或多个SKAction调用来处理这个动画会更好,但我不确定如何实现它.
思考?
到目前为止我在我的场景类中的代码(这只是在屏幕上激活了一次背景)
- (void)addBackgroundTileAtPoint:(CGPoint)point { SKSpriteNode *bg = [SKSpriteNode spriteNodeWithImageNamed:@"background"]; bg.anchorPoint = CGPointZero; bg.position = point; bg.name = @"background"; bg.zPosition = -99; [self addChild:bg]; SKAction *sequence = [SKAction sequence:@[ [SKAction moveByX:-(bg.size.width * 2) y:0 duration:10],[SKAction removeFromParent] ]]; [bg runAction: sequence]; }
解决方法
我在上一个开源项目中为一个特殊的需求做了一个名为SKScrollingNode的小组件:
SprityBird.
即使有3层或4层(视差),FPS也不是问题,但您可能需要自己尝试.
要使用它,您只需像任何其他节点一样添加它并给它一个scrollingSpeed likeo:
back = [SKScrollingNode scrollingNodeWithImageNamed:@"back" inContainerWidth:WIDTH(self)]; [back setScrollingSpeed:BACK_SCROLLING_SPEED]; [self addChild:back];
SKScrollingNode.h
@interface SKScrollingNode : SKSpriteNode @property (nonatomic) CGFloat scrollingSpeed; + (id) scrollingNodeWithImageNamed:(Nsstring *)name inContainerWidth:(float) width; - (void) update:(NSTimeInterval)currentTime; @end
SKScrollingNode.m
@implementation SKScrollingNode + (id) scrollingNodeWithImageNamed:(Nsstring *)name inContainerWidth:(float) width { UIImage * image = [UIImage imageNamed:name]; SKScrollingNode * realNode = [SKScrollingNode spriteNodeWithColor:[UIColor clearColor] size:CGSizeMake(width,image.size.height)]; realNode.scrollingSpeed = 1; float total = 0; while(total<(width + image.size.width)){ SKSpriteNode * child = [SKSpriteNode spriteNodeWithImageNamed:name ]; [child setAnchorPoint:CGPointZero]; [child setPosition:CGPointMake(total,0)]; [realNode addChild:child]; total+=child.size.width; } return realNode; } - (void) update:(NSTimeInterval)currentTime { [self.children enumerateObjectsUsingBlock:^(SKSpriteNode * child,NSUInteger idx,BOOL *stop) { child.position = CGPointMake(child.position.x-self.scrollingSpeed,child.position.y); if (child.position.x <= -child.size.width){ float delta = child.position.x+child.size.width; child.position = CGPointMake(child.size.width*(self.children.count-1)+delta,child.position.y); } }]; } @end