Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you move an IOS SKSprite at a consistent speed

Playing around with SKSprites in the IOS SpriteKit, and I basically want to have a sprite randomly move a certain direction for a certain distance, then pick a new random direction and distance.. Simple enough, create a method that generates the random numbers then creates the animation and in the completion block of the animation have it callback the same routine.

THis does work, but it also keeps the animation from moving at the same velocity since the animations are all based on duration.. If the object has to move 100 it moves at 1/2 the speed it moves if the next random tells it to move 200... So how the heck do I have it move with a consistent speed?

like image 282
Speckpgh Avatar asked Sep 30 '13 23:09

Speckpgh


1 Answers

@Noah Witherspoon is correct above - use Pythagorus to get a smooth speed:

//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];
like image 139
AndyOS Avatar answered Oct 11 '22 01:10

AndyOS