繁体   English   中英

SpriteKit:如何将触摸变成匀速的矢量?

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

我正在使用触摸设置SpriteKit节点的运动。 目前,我这样做:

 //(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)];
}

这对于使节点根据用户滑动的速度移动不同的速度非常有效。 哦,安娜,如果那只是我想要的!

我实际希望获得的效果是,每个节点以均匀的速度移动,无论它们被刷了多快。 似乎我必须进行某种计算,才能从向量中删除幅度,但保留方向,这超出了我的范围。

这可能吗?

您走在正确的轨道上; 您正在寻找的东西就是您已经在计算的触摸运动矢量的归一化矢量 您可以通过计算起始向量的长度并将其每个分量除以该长度,然后将它们乘以您希望最终向量具有的长度(或本例中的速度)来获得。 在代码中:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM