我做了一个randomNumber类,(用于练习和)用于计算屏幕上一个对象的随机位置并且它正常工作,除了它有时将精灵放出屏幕.x和y坐标更小屏幕高度和宽度。但它没有在屏幕上显示。
整个程序基本上是随机地将一个对象的实例放在屏幕内。
randomNumber.h
#import <Foundation/Foundation.h>
#import <SpriteKit/SpriteKit.h>
@interface randomNumber : NSObject
-(int)randNumX:(int) max :(SKSpriteNode *) sprite;
-(int)randNumY:(int) max :(SKSpriteNode *) sprite;
@end
randomNumber.m
#import "randomNumber.h"
@implementation randomNumber
-(int)randNumX:(int) max :(SKSpriteNode *) sprite {
int _spriteW = sprite.frame.size.width;
int _random = (arc4random() % (max - _spriteW));
NSLog(@"The x value is %d", _random);
return _random;
}
-(int)randNumY:(int) max :(SKSpriteNode *) sprite {
int _spriteH = sprite.frame.size.height;
int _random = (arc4random() % (max - _spriteH));
NSLog(@"The y value is %d", _random);
return _random;
}
@end
MyScene.m(仅限initilazeMole方法)
-(void) initilazeMole {
int x = [self.rndNum randNumX:(self.scene.size.width):(self.mole)];
int y = [self.rndNum randNumY:(self.scene.size.height):(self.mole)]
self.mole = [SKSpriteNode spriteNodeWithImageNamed:@"spaceship"];
self.mole.anchorPoint = CGPointMake(0,0);
self.mole.position = CGPointMake(x,y);
SKAction *pulseRed = [SKAction sequence:@[
[SKAction colorizeWithColor:[SKColor redColor] colorBlendFactor:1.0 duration:0.5],
[SKAction waitForDuration:0.1],
[SKAction colorizeWithColorBlendFactor:0.0 duration:1.0]]];
[self.mole runAction: pulseRed];
NSLog(@"mole x position: %f", self.mole.position.x);
NSLog(@"mole y position: %f", self.mole.position.y);
[self addChild:self.mole];
}
我真的不明白为什么它会把它放在屏幕上,因此我会生成一个最大可能的随机数(屏幕宽度 - 精灵宽度)和(屏幕高度 - 精灵高度)
我的项目设置是针对横向模式的iphone 3.5英寸设置的。
知道我的代码出错了吗?
答案 0 :(得分:2)
试试这个:
- (CGPoint) randomPointWithinContainerSize:(CGSize)containerSize forViewSize:(CGSize)size {
NSLog(@"move");
CGFloat xRange = containerSize.width - size.width;
CGFloat yRange = containerSize.height - size.height;
CGFloat minX = (containerSize.width - xRange) / 2;
CGFloat minY = (containerSize.height - yRange) / 2;
int randomX = (arc4random() % (int)floorf(xRange)) + minX;
int randomY = (arc4random() % (int)floorf(yRange)) + minY;
return CGPointMake(randomX, randomY);
}
然后替换:
int x = [self.rndNum randNumX:(self.scene.size.width):(self.mole)];
int y = [self.rndNum randNumY:(self.scene.size.height):(self.mole)]
self.mole = [SKSpriteNode spriteNodeWithImageNamed:@"spaceship"];
self.mole.anchorPoint = CGPointMake(0,0);
self.mole.position = CGPointMake(x,y);
使用:
self.mole.position = [self randomPointWithinContainerSize:self.scene.size forViewSize:self.mole.bounds.size];