如何以一致的速度移动IOS SKSprite

如何以一致的速度移动IOS SKSprite,ios,sprite-kit,skspritenode,skaction,Ios,Sprite Kit,Skspritenode,Skaction,在IOS SpriteKit中玩SKSprites,我基本上想让一个sprite随机移动某个方向一定距离,然后选择一个新的随机方向和距离。。非常简单,创建一个生成随机数的方法,然后创建动画,并在动画的完成块中使其回调相同的例程 这确实有效,但也可以防止动画以相同的速度移动,因为动画都基于持续时间。。如果对象必须移动100,它将以1/2的速度移动,如果下一个随机命令它移动200。。。那么我该如何让它以一致的速度移动呢?@Noah Witherspoon在上面是正确的-使用毕达哥拉斯获得平稳的速度:

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


这确实有效,但也可以防止动画以相同的速度移动,因为动画都基于持续时间。。如果对象必须移动100,它将以1/2的速度移动,如果下一个随机命令它移动200。。。那么我该如何让它以一致的速度移动呢?

@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];

作为对AndyOS答案的扩展,如果你只想沿着一个轴移动(例如,
X
),你可以通过这样做来简化数学:

CGFloat distance = fabs(destination.x - node.position.x);

使用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
})

您应该发布用于确定(并设置动画)新位置的代码。你的问题的基本答案是动画的持续时间应该是当前位置和下一个位置之间距离的固定倍数,但是通过修改当前代码可以更容易地解释。我确实这样做了,虽然它确实起作用,但看起来很难理解,我认为可能会有一些东西,比如以速度移动到xy,而不是以持续时间为基础。这种模型,你计算每移动像素的持续时间,然后乘以你需要移动的像素数,如果同时移动x和y,则需要考虑,因为1个像素的对角线实际上比1个像素的左右距离大(2对1的平方根),假设像素本身是正方形的。API目前没有类似的内容,但您可以自由提交请求。同时处理X和Y方向的距离的解决方案是使用。谢谢,是的,我知道如何计算角速度,只是觉得有点笨拙而已。我知道api是围绕持续时间编写的,而不是速度,但如果我们试图捕捉物理学,速度和距离可能是比简单的距离和时间更好的模型。