保持两个精灵之间的恒定距离

时间:2015-03-01 22:50:28

标签: ios objective-c sprite-kit distance

这是一个距离公式,我通过更新方法来跟踪2个精灵之间的距离:

-(void)distance
{
    double dx = (_spriteA.position.x - _spriteB.position.x);  //(x2 - x1);
    double dy = (_spriteA.position.y - _spriteB.position.y);  //(y2 - y1);
    dist = sqrt(dx*dx + dy*dy);
}

-(void)update:(NSTimeInterval)currentTime
{
    [self distance]; //Calculate A & B distance
    if (dist > 50)
    {
        //What to write here to keep a constant distance between A & B?
        [_spriteB runAction:[SKAction moveTo:(_spriteA.position) duration:1]];
    }
}

跟踪距离很好,但if语句有问题。特别是在精灵B上运行的实际动作。最后发生的事情是精灵B以一种溜溜球的方式不停地向精灵A移动 - 即使精灵A没有移动。我需要精灵B才能在精灵A移动时移动并保持50的距离。精灵A仅在人触摸屏幕时移动。请帮忙。

1 个答案:

答案 0 :(得分:1)

您可以使用SKConstraint类来维护两个节点之间的距离。
例如:

let node1 = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(20, 10))
node1.position = CGPointMake(self.size.width/2, self.size.height/2)
self.addChild(node1)

let node2 = SKSpriteNode(color: UIColor.blueColor(), size: CGSizeMake(10, 20))
node2.position = CGPointMake(self.size.width/2, self.size.height/2 - 50)
self.addChild(node2)

// The upper and lower limit is set to 50 to maintain a constant distance.
let constraint = SKConstraint.distance(SKRange(lowerLimit: 50, upperLimit: 50), toNode : node1) 
node2.constraints = [constraint]

node1.runAction(SKAction.moveToY(100, duration: 2.0))

目标C

SKSpriteNode *node1 = [[SKSpriteNode alloc] initWithColor:[UIColor redColor]
                                                    size:CGSizeMake(20, 10)];
node1.position = CGPointMake(self.size.width/2, self.size.height/2);
[self addChild:node1];

SKSpriteNode *node2 = [[SKSpriteNode alloc] initWithColor:[UIColor redColor]
                                                     size:CGSizeMake(10, 20)];
node2.position = CGPointMake(self.size.width/2, self.size.height/2 - 50);
[self addChild:node2];

// The upper and lower limit is set to 50 to maintain a constant distance.
SKConstraint *constraint = [SKConstraint distance:[SKRange rangeWithLowerLimit:50 upperLimit:50] toNode:node1];
node2.constraints = @[constraint];

[node1 runAction:[SKAction moveToY:100 duration:2.0]];