8

在IOS SpriteKit中玩SKSprites,我基本上想让一个精灵随机移动某个方向一定距离,然后选择一个新的随机方向和距离。很简单,创建一个生成随机数然后创建的方法动画和动画的完成块有它回调相同的例程。

这确实有效,但它也阻止了动画以相同的速度移动,因为动画都是基于持续时间的。如果对象必须移动 100,它会以 1/2 的速度移动,如果下一个随机告诉它它移动move 200... 那么我怎么让它以一致的速度移动呢?

4

3 回答 3

14

@Noah Witherspoon 在上面是正确的 - 使用毕达哥拉斯来获得平稳的速度:

//the node you want to move
SKNode *node = [self childNodeWithName:@"spaceShipNode"];

//get the distance between the destination position and the node's position
double distance = sqrt(pow((destination.x - node.position.x), 2.0) + pow((destination.y - node.position.y), 2.0));

//calculate your new duration based on the distance
float moveDuration = 0.001*distance;

//move the node
SKAction *move = [SKAction moveTo:CGPointMake(destination.x,destination.y) duration: moveDuration];
[node runAction: move];
于 2013-10-01T21:53:48.593 回答
4

使用Swift 2.x我已经用这个小方法解决了:

func getDuration(pointA:CGPoint,pointB:CGPoint,speed:CGFloat)->NSTimeInterval {
    let xDist = (pointB.x - pointA.x)
    let yDist = (pointB.y - pointA.y)
    let distance = sqrt((xDist * xDist) + (yDist * yDist));
    let duration : NSTimeInterval = NSTimeInterval(distance/speed)
    return duration
}

使用这种方法,我可以使用 ivar myShipSpeed 并直接调用我的操作,例如:

let move = SKAction.moveTo(dest, duration: getDuration(self.myShip.position,pointB: dest,speed: myShipSpeed))
self.myShip.runAction(move,completion: {
  // move action is ended
})
于 2016-03-17T11:25:26.353 回答
3

作为@AndyOS答案的扩展,如果您只想继续前进one axisX例如),您可以通过这样做来简化数学:

CGFloat distance = fabs(destination.x - node.position.x);
于 2015-01-16T08:58:28.713 回答