我创建了我的SKScene子类,该子类设置了锚点,然后为该世界添加了一个SKSpriteNode,该世界有多个用于障碍物,玩家等的SKSpriteNodes。我也将重点放在
我遇到的问题是,当我将场景的锚点设置为(0.5,0.5)时,我添加到世界上的任何子节点的位置都始于世界的中心。如何固定节点的位置,以便position =(0,0)将位于world节点的左下角,并向其中添加任何子节点而不是中心?
@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);
}
如果要将世界精灵的原点设置在左下角,只需将其设置为锚点即可。
world.anchorPoint = CGPointMake(0,0);
这样,世界精灵的坐标系将与场景默认坐标系一样。
确保删除该行:
self.anchorPoint = CGPointMake(0.5, 0.5);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句