我创建了我的SKScene子类,它设置了anchorpoint,然后为世界添加了一个SKSpriteNode,世界上有多个SKSpriteNodes用于障碍,玩家等。我也是以
为中心我遇到的问题是,当我将场景的锚点设置为(0.5,0.5)时,我添加到世界的任何子节点的位置都从世界的中心开始。如何修复节点的位置,使position =(0,0)位于世界节点的左下角,并添加任何子节点而不是中心?
@implementation LevelScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
NSLog(@"width:%f height:%f", self.view.bounds.size.width, self.view.bounds.size.height);
// set the physics body
self.physicsWorld.gravity = CGVectorMake(0,-5);
self.physicsWorld.contactDelegate = self;
self.anchorPoint = CGPointMake(0.5, 0.5);
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"LevelScene" ofType:@"plist"]];
NSString *backgroundImage = [plistDict objectForKey:@"background"];
// add a node that holds the background
background = [SKSpriteNode spriteNodeWithTexture:[SKTexture textureWithImageNamed:backgroundImage] size:CGSizeMake(1024, 768)];
background.position = CGPointMake(0, 0);
[self addChild:background];
world = [SKSpriteNode spriteNodeWithColor:[SKColor brownColor] size:CGSizeMake(1024, 768)];
world.position = CGPointMake(0, 0); // this should be bottom-left
world.size = CGSizeMake(1024, 768);
world.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:world.frame];
world.physicsBody.categoryBitMask = worldCategory;
[self addChild:world];
// load in the game tiles (these are non-dynamic tiles the player can use)
[self loadInTiles];
// add in game object to the world skspritenode - this just creates a subclass of skspritenode and sets position to 0,0
[self addGameObject:CGPointMake(0, 0)];
...
}
// ...setup functions, input handling, etc
-(void)didSimulatePhysics {
// setup the player to move depending on their direction
[player updatePosition];
[self centreOnNode:player];
}
-(void)centreOnNode: (SKSpriteNode *)node {
CGPoint cameraPositionInScene = [node.scene convertPoint:node.position fromNode:node.parent];
CGFloat x = node.parent.position.x - cameraPositionInScene.x;
CGFloat y = node.parent.position.y - cameraPositionInScene.y;
NSLog(@"camera x:%f y:%f", x, y);
NSLog(@"world frame origin x:%f y:%f", world.frame.origin.x, world.frame.origin.y);
node.parent.position = CGPointMake(x, y);
}
答案 0 :(得分:2)
如果你想将世界精灵的原点设置在左下角,只需设置它的锚点。
world.anchorPoint = CGPointMake(0,0);
有了这个,世界精灵的坐标系就像是场景的默认坐标系。
请务必删除该行:
self.anchorPoint = CGPointMake(0.5, 0.5);
答案 1 :(得分:1)
替换此行:
world.position = CGPointMake(0, 0);
由此:
world.position = CGPointMake(-CGRectGetMidX(self.frame), -CGRectGetMidY(self.frame));
(0,0)
是场景的中心,因为您将SKScene
的锚点设置为(0.5,0.5)