SKNode position not working, always going to defau

2019-02-13 16:17发布

I have fairly well developed SpriteKit game I'm working on, added some code to add a new SKSpriteNode to the Scene, (same as I have done dozens of other places in the code, but for some reason this time it is just ignoring the position I have set for the node, I have tried it by explicit .position = CGPointMake(x,y) and trying the [node setPosition:CGPointMake(x,y)]

Neither work... the node does get added to the scene, but ALWAYS at 0,0, no matter what I do, have checked both the x and y to make sure they are valid and in the range of the scene, and tried to use explicit floats etc, and it doesn't matter what I do, this node always shows up at 0,0 and it makes absolutely no sense. I am doing everything the same I am doing with dozens of other nodes over the course of game play but this node just won't show up anywhere but 0,0 no matter what I do:

int width = 64;
SKSpriteNode *node = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(width,25)];
node.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node.size];
node.physicsBody.dynamic = NO;
node.physicsBody.categoryBitMask=nodeCategory;
node.name=@"node";
node.position = CGPointMake(200,250);
//Have also tried [node setPosition:CGPointMake(200,250);
[self addChild:node];

I am completely at a loss here, I've tried adding .0 to the inputs to the CGPointMake to ensure they are handled as floats nothing... No matter what I do with this node, when it is added to the scene it always defaults to the 0,0 position, and I am frustrated, I am adding all sorts of nodes without incident, just something about this node add that is just not working and can't figure out what is different or why.

1条回答
Ridiculous、
2楼-- · 2019-02-13 16:23

I've been having this same issue. I have a subclass of SKSpriteNode that most of my in-game nodes use as a superclass. I've added this method, which I use whenever I run into the positioning problem:

- (void)refreshPhysicsBodyAndSetPosition:(CGPoint)position {

    /*
     * Weird thing here: if I just set the position of these nodes, they
     * end up at position (0,0). However, if I remove the physics body, set
     * the position, and then re-add the physics body, the nodes are
     * placed correctly.
     */

    SKPhysicsBody *tempPhysicsBody = self.physicsBody;
    self.physicsBody = nil;

    // Position and re-add physics body
    self.position = position;
    self.physicsBody = tempPhysicsBody;
}

Obviously, this isn't a real answer to the issue, but it's a workaround that may help some of you. I have a question opened on the Apple Developer forum, which you can view here:

https://devforums.apple.com/thread/222332

Hoping I hear back soon.

查看更多
登录 后发表回答