如何在视图中保持下降的spritenodes?

时间:2014-06-16 16:28:37

标签: ios xcode sprite-kit gravity skspritenode

我正在尝试制作类似于raywenderlich:初学者图片的精灵套件教程的iphone游戏。我试图在portait模式下进行此操作,而不是在教程中使用的横向模式。我使用了这段代码并进行了调整,以便精灵从屏幕顶部落到底部,但有时精灵只有一半在视野之外,甚至更多。

http://www.raywenderlich.com/42699/spritekit-tutorial-for-beginners

这就是我得到的:

SKSpriteNode * monster = [SKSpriteNode spriteNodeWithImageNamed:@"AcornFinal.png"];

// Determine where to spawn the monster along the X axis
int minX = self.frame.size.width;
int maxX = self.frame.size.width - monster.size.width;
int rangeX = maxX + minX;
int actualX = (arc4random() % + rangeX);

// Random position along the X axis as calculated above
// This describe from which way the acorns move
// - means moving from top to the right and + means moving from the top to the left
monster.position = CGPointMake(actualX,self.frame.size.height);
[self addChild:monster];

// Determine speed of the monster
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;



// Create the actions
SKAction * actionMove = [SKAction moveTo:CGPointMake(actualX,-monster.size.height) duration:actualDuration];
SKAction * actionMoveDone = [SKAction removeFromParent];
[monster runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];

所以我认为问题可能出在这四行代码中:

// Determine where to spawn the monster along the X axis
int minX = self.frame.size.width;
int maxX = self.frame.size.width - monster.size.width;
int rangeX = maxX + minX;
int actualX = (arc4random() % + rangeX);

如何修复此错误>?

修改

解决方案是将前四行改为

int minX = monster.size.width;
int maxX = self.frame.size.width - monster.size.width;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX)+minX;

1 个答案:

答案 0 :(得分:0)

如果想要将怪物保持在屏幕的水平范围内,那么你的数学似乎有点像。如果精灵的锚点是0.5,0.5并且场景大小等于屏幕,我认为它应该是:

int minX = monster.size.width / 2; 
int maxX = self.frame.size.width - monster.size.width;
int x = (arc4random() % + maxX) +  minX;