SpriteKit:如何将触摸变成匀速的矢量? [英] SpriteKit: how to turn touches into vectors of uniform speed?

查看:76
本文介绍了SpriteKit:如何将触摸变成匀速的矢量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用触摸使SpriteKit节点运动.目前,我正在这样做:

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.

这可能吗?

推荐答案

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

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;

这篇关于SpriteKit:如何将触摸变成匀速的矢量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆