IOS SpriteKit で SKSprites をいじって、私は基本的に、スプライトを特定の方向に特定の距離だけランダムに移動させ、新しいランダムな方向と距離を選択させたいと考えています。アニメーションとアニメーションの完了ブロックで、同じルーチンをコールバックします。
これは機能しますが、アニメーションはすべて持続時間に基づいているため、アニメーションが同じ速度で移動することもありません。 move 200... では、どうすれば一貫した速度で移動できるのでしょうか?
IOS SpriteKit で SKSprites をいじって、私は基本的に、スプライトを特定の方向に特定の距離だけランダムに移動させ、新しいランダムな方向と距離を選択させたいと考えています。アニメーションとアニメーションの完了ブロックで、同じルーチンをコールバックします。
これは機能しますが、アニメーションはすべて持続時間に基づいているため、アニメーションが同じ速度で移動することもありません。 move 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];
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
})
@AndyOSの回答の拡張として、one axis
(X
たとえば)のみに沿って移動する場合は、代わりにこれを行うことで数学を簡素化できます。
CGFloat distance = fabs(destination.x - node.position.x);