Sprite Kit中的简单碰撞

时间:2015-11-01 17:46:27

标签: ios objective-c sprite-kit

我有两个节点。球员和敌人。我希望Enemy节点一旦足够接近就跟随Player节点,当Enemy节点与Player节点发生碰撞时它将停止。我得到的是Enemy节点在Player之上,两个节点都被推送。我想过以某种方式阻止Enemy节点与Player的碰撞,但在我看来它应该是一个更清洁方式。

(我通过在更新时更改它来移动Enemy节点。)

这是我的GameScene.sks:

character and enemy options from GameScene

-(void)didMoveToView:(SKView *)view {

    player = [self childNodeWithName:@"character"];
    enemy  = [self childNodeWithName:@"enemy"];
    self.physicsWorld.contactDelegate = self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    for (UITouch *touch in touches) {
        moveToTouch = [touch locationInNode:self];
        SKNode *tile = [self nodeAtPoint:moveToTouch];
        if([tile.name isEqualToString:@"tile"])
        {
            moveToTouch = tile.position;
        }
    }
}

-(void)update:(CFTimeInterval)currentTime {

    [self walk:player to:moveToTouch];

    if((SDistanceBetweenPoints(enemy.position, player.position) < 200))
    {
        [self walk:enemy to:player.position];
    }


}

-(void)walk:(SKNode*)node to:(CGPoint)moveTo
{
    if (CGPointEqualToPoint(moveTo, CGPointZero))
    {
        return;
    }


    if(round(moveTo.y) != round(node.position.y))
    {

        if(moveTo.y > node.position.y)
        {
            node.position = CGPointMake(node.position.x,node.position.y+2);
        }
        else if (moveTo.y < node.position.y)
        {
            node.position = CGPointMake(node.position.x,node.position.y-2);
        }

    }else if(round(moveTo.x) != round(node.position.x))
    {

        if(moveTo.x > node.position.x)
        {
            node.position = CGPointMake(node.position.x+2,node.position.y);
        }
        else if (moveTo.x < node.position.x)
        {
            node.position = CGPointMake(node.position.x-2,node.position.y);
        }

    }

    float distance = SDistanceBetweenPoints(node.position, moveTo);
    if (distance < 1.0){
        moveToTouch = CGPointZero;
    }

}

1 个答案:

答案 0 :(得分:1)

我不知道你是如何设置敌人跟随玩家的。 但你可以尝试

  • 将敌人动态设为假
  • 或将速度设为0

使用碰撞检测来了解碰撞的时间。