嗨我需要随机地在屏幕上沿x轴底部生成我的精灵气球。我使用了Ray Wenderliches网站上的代码,但当我点击开始产卵的按钮时,他们不会产卵?
@implementation MyScene2
- (void)addMonster {
// Create sprite
SKSpriteNode * monster = [SKSpriteNode spriteNodeWithImageNamed:@"balloon11.png"];
// Determine where to spawn the monster along the X axis
int minX = monster.size.height / 2;
int maxX = self.frame.size.height - monster.size.height / 2;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX) + minX;
// Create the monster slightly off-screen along the right edge,
// and along a random position along the X axis as calculated above
monster.position = CGPointMake(self.frame.size.width + monster.size.width/2, actualX);
[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(-monster.size.width/2, actualX)
duration:actualDuration];
SKAction * actionMoveDone = [SKAction removeFromParent];
[monster runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];
}
- (void)updateWithTimeSinceLastUpdate:(CFTimeInterval)timeSinceLast {
self.lastSpawnTimeInterval += timeSinceLast;
if (self.lastSpawnTimeInterval > 1) {
self.lastSpawnTimeInterval = 0;
[self addMonster];
}
}
- (void)update:(NSTimeInterval)currentTime {
// Handle time delta.
// If we drop below 60fps, we still want everything to move the same distance.
CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
self.lastUpdateTimeInterval = currentTime;
if (timeSinceLast > 1) { // more than a second since last update
timeSinceLast = 1.0 / 60.0;
self.lastUpdateTimeInterval = currentTime;
}
[self updateWithTimeSinceLastUpdate:timeSinceLast];
}
答案 0 :(得分:1)
您的主要问题在于以下代码:
monster.position = CGPointMake(self.frame.size.width + monster.size.width/2 , actualX);
该方法的工作方式如下:CGPointMake( x_coord , y_coord );
。
现在,您将x值设置为帧的宽度加上精灵的宽度,因此这将导致精灵在屏幕上生成。你给y坐标随机化的值。相反,使用
CGPointMake(actualX , self.frame.size.height);
此代码存在另一个问题。这些坐标基于视图,但monster.position
基于SKScene
。 SKScene
来源通常与视图的原点不匹配。所以你必须这样做:
monster.position = [CGPointMake(actualX , self.frame.size.height); locationInNode: self];
另外,我注意到您使用frame.size.width
表示预期的Y轴坐标,frame.size.height
表示预期的X轴坐标。宽度用于x,高度用于y,因此请确保正确使用它们。