我建议跳过滚动操作并改用更新方法。还有一种方法可以同时只有几个背景部分。
首先,您需要创建纹理图集并在其中添加所有这些图像。
其次,您需要在场景中创建两个属性:
SKSpriteNode *firstNode;
SKSpriteNode *secondNode;
我还建议将所述图集添加为实例变量,例如
SKTextureAtlas *atlas;
在场景的init方法或者你的其他setup方法中,你需要创建和定位这些节点。也不要忘记在此之前创建纹理图集变量。
self.firstNode = [[SKSpriteNode alloc] initWithTexture:[self.atlas textureNamed:@"texture1"]];
self.secondNode = [[SKSpriteNode alloc] initWithTexture:[self.atlas textureNamed:@"texture2"]];
通常在这种情况下,我将这些精灵的锚点更改为 CGPointMakeZero,以简化定位计算。可以这样做:
self.firstNode.anchorPoint = CGPointZero;
self.secondNode.anchorPoint = CGPointZero;
这有助于精灵的 (0,0) 点位于精灵的左下角。
所以现在我们可以根据需要将精灵添加到我们的世界中,可以直接添加到场景中,也可以添加到中间世界节点中。
self.firstNode.position = CGPointMake(0, 0); // or CGPointZero
self.secondNode.position = CGPointMake(self.firstNode.size.width, 0);
现在我们有两个彼此跟随的节点。
我们如何滚动?我们需要更改更新方法。我们需要创建新的属性 CFTimeInterval lastUpdate,我们需要它来存储自上次更新以来经过的时间,并据此计算我们需要移动节点的像素数量。
-(void)update:(CFTimeInterval)currentTime {
if (!self.lastUpdate) {
self.lastUpdate = currentTime;
self.secondsCounter = 0;
return;
}
double delta = currentTime - self.lastUpdate;
self.lastUpdate = currentTime;
[self updateGroundScrollingWithDelta:delta];
}
这是实际滚动节点的方法(您需要在别处定义一些 moveSpeed 或将其更改为某个常量):
- (void)updateGroundScrollingWithDelta:(double)delta
{
self.firstNode.position = CGPointMake(self.firstNode.position.x - delta * moveSpeed, self.firstNode.position.y);
self.secondNode.position = CGPointMake(self.secondNode.position.x - delta * moveSpeed, self.secondNode.position.y);
if (self.firstNode.position.x < -self.firstNode.size.width) {
self.firstNode.position = CGPointMake(self.secondNode.position.x + self.secondNode.size.width - 1, self.firstNode.position.y);
// here you need to change the texture of your node
}
if (self.secondNode.position.x < -self.secondNode.size.width) {
self.secondNode.position = CGPointMake(self.firstNode.position.x + self.firstNode.size.width - 1, self.secondNode.position.y);
// here you need to change the texture of your node
}
}
在这个方法中,我们将节点移动一定数量的像素,然后检查 - 如果节点离左边太远并且不可见,我们将节点附加到另一个节点的末尾,所以我们的滚动看起来无缝。
如 cmets 中所述,您需要在某处更改精灵的纹理。
为了跟踪纹理,我建议创建一个实例变量int counter。显然它应该从 2 开始,因为我们已经在两个节点上安排了纹理编号 0 和 1。
您可以使用它来查看下一个纹理。所以在这里我建议一种获取下一个纹理的方法:
- (SKTexture *)nextBackgroundTexture
{
NSString *nextName = [NSString stringWithFormat:@"myTexture%d", self.counter];
self.counter++;
return [self.atlas textureNamed:nextName];
}
所以现在您只需要在需要时更新计数器并交换纹理。
正如我所说,您可以将这些行放在方法的注释部分中以滚动节点:
self.firstNode.texture = [self nextBackgroundTexture];
和
self.secondNode.texture = [self nextBackgroundTexture];
这样,您将在内存中只有两个纹理,并且滚动可以正常工作。 (实际上这不是真的,因为 Sprite Kit 会缓存使用过的纹理,但希望它会在将来释放它们)。
希望这会有所帮助。
附:实际上,在重新阅读您的问题后,我发现您需要垂直滚动,改变这一点相当简单,您需要在开始时以不同的方式定位节点,使用 y 坐标和节点高度而不是宽度来查找位置。
同样在滚动时改变 Y 值而不是 X 值。
我把这个作为练习留给你。