SpriteKit: how to turn touches into vectors of uniform speed?

江枫思渺然 提交于 2019-12-12 01:28:26

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/29808621/spritekit-how-to-turn-touches-into-vectors-of-uniform-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!