我如何在视图中保持下降的精灵节点?
Posted
技术标签:
【中文标题】我如何在视图中保持下降的精灵节点?【英文标题】:How do i keep falling spritenodes within the view? 【发布时间】:2014-06-16 16:28:36 【问题描述】:我正在尝试为初学者制作一个类似于 raywenderlich 的 iphone 游戏:sprite Kit 教程。但是,我试图在纵向模式下进行此操作,而不是在教程中使用的横向模式。我使用这段代码并对其进行了调整,使精灵从屏幕顶部落到底部,但有时精灵在视图之外的一半甚至更多。
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.5, 0.5 并且场景大小等于屏幕我认为应该是:
int minX = monster.size.width / 2;
int maxX = self.frame.size.width - monster.size.width;
int x = (arc4random() % + maxX) + minX;
【讨论】:
感谢您,我发现了我的错误,我不得不将您的 int x 行更改为: int actualX = (arc4random() % rangeX)+minX;但现在它工作正常,谢谢! 我无法完全理解我计算的哪一部分没有凝胶,但如果你弄清楚了,那么我想这一切都很好! :-)以上是关于我如何在视图中保持下降的精灵节点?的主要内容,如果未能解决你的问题,请参考以下文章