SpriteKit bodyWithTexture:sprite离开场景的边界

时间:2014-12-11 06:27:22

标签: sprite-kit

我最近发现了一种新的方法来给精灵一个物理身体,而不仅仅是使用一个圆圈,但是当我使用这个新方法时,精灵将会击中屏幕的边界并推进并离开。

我有场景边框设置:

self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

这是我正在尝试的方法:

zombie.physicsBody = [SKPhysicsBody bodyWithTexture:zombie.texture size:zombie.size];

我的精灵如何推出现场?

位掩码:

self.physicsWorld.contactDelegate = self;

zombie.physicsBody.categoryBitMask = playerCategory;
zombie.physicsBody.contactTestBitMask = gearCategory;
zombie.physicsBody.collisionBitMask = 1;

1 个答案:

答案 0 :(得分:0)

我不确定你为什么遇到这个问题。我不知道为什么你需要使用更新方法。如果你正在设置一个速度,那么精灵将保持这个速度直到某些东西改变它。我将分享我的视图控制器和场景。我没有遇到同样的问题。这和你正在做什么有什么区别?

你试过没有bodyWithTexture吗?我知道它是spritekit的最新成员。也许你的纹理形状是奇怪的,并导致问题。尝试使用bodyWithRectangleOfSize

进行操作

<强>的ViewController

@implementation GameViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Configure the view.
    SKView * skView = (SKView *)self.view;
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;
    /* Sprite Kit applies additional optimizations to improve rendering performance */
    skView.ignoresSiblingOrder = YES;

    // Create and configure the scene.
    GameScene *scene = [[GameScene alloc]initWithSize:skView.frame.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;

    // Present the scene.
    [skView presentScene:scene];
}


@end

<强> GameScene

@implementation GameScene

SKSpriteNode *_test;

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
        self.physicsWorld.gravity = CGVectorMake(0, 0);
        _test = [[SKSpriteNode alloc]initWithColor:[SKColor redColor] size:CGSizeMake(10, 10)];
        _test.position = CGPointMake(self.size.width/2, self.size.height/2);
        _test.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_test.size];

        [self addChild:_test];
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    for (UITouch *touch in touches) {
        CGPoint touchPos = [touch locationInNode:self];

        CGPoint newPosition = CGPointMake(touchPos.x - _test.position.x, touchPos.y - _test.position.y);
        CGFloat angle = atan2(newPosition.y, newPosition.x);
        CGPoint normalized = CGPointMake(cos(angle), sin(angle));

        _test.physicsBody.velocity = CGVectorMake(normalized.x * 200, normalized.y * 200);

    }
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

@end