Reputation: 863
I'm attempting to have a character move across the screen from point A to point B on user touch.
I'm currently doing this with SKActions (in a group). However, I've noticed that SKActions take a duration, so there will be not constant movement speed which is a deal breaker. Closer distances will cause the character to move slower while far way distances make the character move faster.
Is there a better way for doing this? I was thinking in using the -update method in the scene but not sure what would be the best way to tie this into the touch events.
Any recommendations?
Upvotes: 3
Views: 400
Reputation: 972
All you need to do is calculate the duration yourself using the distance and speed.
speed = distance/time, time being your duration, so solve for t.
Using some pseduo code here:
function moveToWithSpeed(p1, endPoint: p2, speed: speed)
{
//credit: http://stackoverflow.com/questions/1906511/how-to-find-the-distance-between-two-cg-points
CGFloat xDist = (p2.x - p1.x);
CGFloat yDist = (p2.y - p1.y);
CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist));
duration = distance/speed
SKAction.moveTo(p2, duration: duration);
}
The rest I think you can figure out yourself.
Upvotes: 2
Reputation: 12904
You can still do this with SKAction and grouping...
First you'll want to calculate the distance between the two points, a^2 + b^2 = c^2
(Pythagorean Theorem) kind of thing. Then figure out from a constant speed how quickly or how slow the character should move based off c^2.
Then just send that variable to the SKAction
function you make up. That way it's dynamic.
-(SKAction*)startActionWithDuration:(NSTimeInterval)timeInterval {
SKAction* action = [SKAction moveToX:1.0 duration:timeInterval];
return action;
}
Upvotes: 0