如何做冲动物理

时间:2014-03-24 06:22:13

标签: ios iphone sprite-kit physics

好吧,伙计们,我有两个精灵,一个是敌人,当物品出现时,它会移动到地图周围拾取物品,然后使用SKActions,然后我也有他不应该经过的墙。无论如何。我所要做的就是让他在撞墙时反弹。我该怎么做呢?

以下是代码:

//对于敌人墙我有这个代码:

- (void) EnemyBelongings {
EnemyWall = [SKSpriteNode spriteNodeWithImageNamed:@"EnemyWall@2x"];
EnemyWall.name = @"hisWall";
EnemyWall.position = CGPointMake(512, 260);
EnemyWall.xScale = 0.09;
EnemyWall.yScale = 0.09;
EnemyWall.physicsBody.categoryBitMask = PhysicsCategoryEnemyWall;
EnemyWall.physicsBody.contactTestBitMask = PhysicsCategoryEnemy;
EnemyWall.physicsBody.collisionBitMask = 0;
[self addChild:EnemyWall];

}

//对于敌人角色我有这个代码

- (void) Enemy {
    _Enemy = [SKSpriteNode spriteNodeWithImageNamed:@"enemy"];
    _Enemy.position = CGPointMake(520, _Enemy.size.height/1.50);
    _Enemy.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.size.width];
    _Enemy.physicsBody.usesPreciseCollisionDetection = YES;
    _Enemy.physicsBody.categoryBitMask = PhysicsCategoryEnemy;
    _Enemy.physicsBody.contactTestBitMask = PhysicsCategoryEnemyWall;
    _Enemy.physicsBody.collisionBitMask = 0;
    [self addChild:_Enemy];
}

//对于敌人运动我有这个代码

- (void) EnemySpawner {
    [ForEnemy runAction:appear2 completion:^{
    SKAction *wait = [SKAction waitForDuration:1.0];
    [_Enemy runAction:wait];
    SKAction *actionXMove2 = [SKAction moveToX:ForEnemy.position.x duration:0.14];
    SKAction *actionYMove2 = [SKAction moveToY:ForEnemy.position.y duration:0.14];
    [_Enemy runAction:actionYMove2];
    [_Enemy runAction:actionXMove2];
}];

}

-(void)didBeginContact:(SKPhysicsContact *)contact
{
if (contact.bodyA.categoryBitMask == PhysicsCategoryEnemy && contact.bodyB.categoryBitMask 
    == PhysicsCategoryEnemyWall)
{
    SKNode *enemy = contact.bodyA.node;  // a is the enemy here
       // Code here
    SKNode *wall = contact.bodyB.node; // b is the enemy's wall here
       // Code here
}
else if (contact.bodyB.categoryBitMask == PhysicsCategoryEnemy && 
    contact.bodyA.categoryBitMask == PhysicsCategoryEnemyWall)
{
    SKNode *enemy = contact.bodyB.node;
       // Code here
    SKNode *wall = contact.bodyA.node;
       // Code here
}

}

2 个答案:

答案 0 :(得分:1)

您需要在节点的物理实体上applyImpulse使其自然模拟并与其他物理实体进行交互。

请查看我的答案here,了解如何做同样的事。

复制Ray Wenderlich的tutorial中的rwAdd,rwSub,rwMult,rwLength和rwNormalize方法。

然后,尝试使用此代码:

[ForEnemy runAction:appear2 completion:^{
        SKAction *wait = [SKAction waitForDuration:1.0];

        CGPoint offset = rwSub(location, ForEnemy.position);
        CGPoint direction = rwNormalize(offset);
        float forceValue = 200; //Edit this value to get the desired force.
        CGPoint shootAmount = rwMult(direction, forceValue);

        CGVector impulseVector = CGVectorMake(shootAmount.x, shootAmount.y);

        [_Enemy.physicsBody applyImpulse:impulseVector];


         }];

答案 1 :(得分:0)

PhysicsWorld应该自动模拟弹跳。只需设置你的节点'相应的物理属性。寻找恢复原状'属性。它将决定你的物体的弹性。

并且不要使用SKAction来移动你的敌人。这只是传送"你周围的节点。他们在物理世界中没有任何真正的速度(因此不会反弹)。相反,将力施加到您的身体(或手动设置速度矢量)。