I am using touches to set SpriteKit nodes in motion. Currently I do this:
//(previous code turns current touch and last touch into thisP and thatP)...
CGPoint velocity = CGPointMake(thisP.x - lastP.x, thisP.y - lastP.y);
//If the velocity is non-zero, apply it to the node:
if (!CGPointEqualToPoint(velocity, CGPointZero)) {
[[MyNode physicsBody] applyForce:CGVectorMake(velocity.x, velocity.y)];
}
This is very effective at getting the nodes to move different speeds depending on how fast the user swiped. Oh, Anna, if only that was what I wanted!
My actual desired effect is for every node to move at a uniform speed, no matter how fast they were swiped. It seems like I'd have to make some kind of calculation that removes magnitude from the vector but preserves direction, which is beyond me.
Is this possible?
You’re on the right track; the thing you’re looking for is called the normalized vector of the touch-movement vector you’re already calculating. You can obtain that by calculating the length of the starting vector and dividing each of its components by that length, then multiplying them by the length (or in this case the speed) that you want the final vector to have. In code:
float length = hypotf(velocity.x, velocity.y); // standard Euclidean distance: √(x^2 + y^2)
float multiplier = 100.0f / length; // 100 is the desired length
velocity.x *= multiplier;
velocity.y *= multiplier;