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

时间:2013-09-30 23:36:37

标签: ios sprite-kit skspritenode skaction

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

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

3 个答案:

答案 0 :(得分:13)

@Noah Witherspoon在上面是正确的 - 使用Pythagorus来获得平稳的速度:

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

答案 1 :(得分: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
})

答案 2 :(得分:3)

作为 @AndyOS 的答案的扩展,如果您只是沿着one axis(例如X)移动,那么您可以通过这样做来简化数学运算:

CGFloat distance = fabs(destination.x - node.position.x);
相关问题