SpriteKit项目——小妖精漫步----纹理贴图集(Texture Atlas)
// 1. 加载贴图集
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:@"Goblin_Walk"];
// 2. 使用纹理图填充数组
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:28];
for (NSInteger i = 1; i < 29; i++) {
NSString *name = [NSString stringWithFormat:@"goblin_walk_%04d", i];
SKTexture *texture = [atlas textureNamed:name];
[arrayM addObject:texture];
}
_walkFrames = arrayM;
四、小妖精行走Action
创建小妖精图像精灵
SKSpriteNode *goblin = [SKSpriteNode spriteNodeWithTexture:_walkFrames[0]];
goblin.position = CGPointMake(self.size.width / 2, self.size.height / 2);
[self addChild:goblin];
_goblin = goblin;
// 4. 小妖精行走
SKAction *walkAction = [SKAction animateWithTextures:_walkFrames timePerFrame:0.1f];
[goblin runAction:[SKAction repeatActionForever:walkAction]];
五、根据点击位置旋转方向
// 旋转小妖精
CGPoint location = [[touches anyObject] locationInNode:self];
CGPoint offset = CGPointMake(location.x - _goblin.position.x, location.y - _goblin.position.y);
CGFloat angle = atan2f(offset.y, offset.x) - M_PI_2;
_goblin.zRotation = angle;
六、行走不骗
七、添加发呆动画,行走至目标点
/ 计算行走距离
CGFloat distance = sqrtf(powf(offset.x, 2.0) + powf(offset.y, 2.0));
CGFloat duration = distance / self.size.height * 8.0;
// 删除所有操作
[_goblin removeAllActions];
[self goblinRepeatFrame:_walkFrames];
// 定义行走动作
SKAction *moveTo = [SKAction moveTo:to duration:duration];
[_goblin runAction:moveTo completion:^{
[_goblin removeAllActions];
[self goblinRepeatFrame:_idleFrames];
}];