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

在IOS SpriteKit中玩SKSprites,我基本上想要一个精灵随机移动一定距离的某个方向,然后select一个新的随机方向和距离。很简单,创build一个方法,产生随机数然后创buildanimation和animation的完成块中有callback相同的例程。

这是行得通的,但是它也保持animation以相同的速度移动,因为animation全部基于持续时间。如果对象必须移动100,则它以移动的速度移动1/2,如果下一个随机指示它移动移动200 …那么我怎么才能以一致的速度移动?

@Noah威瑟斯庞是正确的以上 – 使用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]; 

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

有了这个方法,我可以使用伊娃myShipSpeed,并直接调用我的行为,例如:

 let move = SKAction.moveTo(dest, duration: getDuration(self.myShip.position,pointB: dest,speed: myShipSpeed)) self.myShip.runAction(move,completion: { // move action is ended }) 

作为@AndyOS答案的一个扩展,如果你只想沿着one axis (例如X )移动,你可以通过这样做简化math:

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