Scaling Physics Bodies in Xcode Spritekit

后端 未结 2 415
终归单人心
终归单人心 2020-12-10 19:38

I recently came across an issue where I would increase the size of a node, but the physics body would remain the same size. I tried to look up solutions to this with no succ

2条回答
  •  既然无缘
    2020-12-10 20:01

    I thought this won't work, but it looks like that physics body is scaled after all. Here is the code which can reproduce physics body scaling on iOS8 :

    - (void)didMoveToView:(SKView *)view {
      /* Setup your scene here */
    
        SKSpriteNode *s = [SKSpriteNode spriteNodeWithColor:[SKColor yellowColor] size:CGSizeMake(100,100)];
        s.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame)+100);
        s.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:s.size];
    
        s.physicsBody.dynamic = YES;
        
        s.physicsBody.affectedByGravity = NO;
    
        [self addChild:s];
        
        [s runAction:[SKAction scaleTo:0.3f duration:5]];
    
        [s.physicsBody applyImpulse:CGVectorMake(0,30)];
      
    }
    

    If I recall correctly , this wasn't worked earlier, but I just tried it and it looks like it work. Still, this is not fully tested and I am not sure if this will mess up the physics simulation. Contact detection will probably work though. I just wanted to show that actual physics bodies are scaled when sprite is scaled . Here is the result:

    From the gif above it can be seen that physics body is scaled along with sprite (without re-creating another different sized physics body). The blue bounding box around the sprite is visual representation of sprite's physics body (enabled in view controller with skView.showsPhysics = YES);

提交回复
热议问题