精灵套件 - 确定滑动精灵的滑动手势矢量 [英] Sprite Kit - Determine vector of swipe gesture to flick sprite
问题描述
我有一个游戏,圆形物体从屏幕底部向上射击,我希望能够滑动它们以向我的滑动方向轻弹它们。我的问题是,我不知道如何计算滑动的矢量/方向,以便使圆形物体以适当的速度在正确的方向上轻弹。
I have a game where circular objects shoot up from the bottom of the screen and I would like to be able to swipe them to flick them in the direction of my swipe. My issue is, I don't know how to calculate the vector/direction of the swipe in order to get the circular object to get flicked in the proper direction with the proper velocity.
我正在使用的静态向量(5,5)需要通过滑动的滑动速度和方向来计算。此外,我需要确保一旦我第一次接触到对象,就不再发生这种情况,以避免双重击中对象。以下是我目前正在做的事情:
The static vector "(5,5)" I am using needs to be calculated by the swipe speed and direction of the swipe. Also, I need to make sure that once I make first contact with the object, it no longer happens, as to refrain from double hitting the object. Here's what I am doing currently:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
CGPoint location = [touch locationInNode:self];
SKNode* node = [self nodeAtPoint:location];
[node.physicsBody applyImpulse:CGVectorMake(5, 5) atPoint:location];
}
}
推荐答案
这里是如何检测滑动手势的示例:
Here's an example of how to detect a swipe gesture:
首先,定义实例变量以存储起始位置和时间。
First, define instance variables to store the starting location and time .
CGPoint start;
NSTimeInterval startTime;
在touchesBegan中,保存触摸事件的位置/时间。
In touchesBegan, save the location/time of a touch event.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Avoid multi-touch gestures (optional) */
if ([touches count] > 1) {
return;
}
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
// Save start location and time
start = location;
startTime = touch.timestamp;
}
定义滑动手势的参数。相应地调整这些。
Define parameters of the swipe gesture. Adjust these accordingly.
#define kMinDistance 25
#define kMinDuration 0.1
#define kMinSpeed 100
#define kMaxSpeed 500
在touchesEnded中,通过比较差异来确定用户的手势是否是滑动开始和结束位置和时间戳之间。
In touchesEnded, determine if the user's gesture was a swipe by comparing the differences between starting and ending locations and time stamps.
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
// Determine distance from the starting point
CGFloat dx = location.x - start.x;
CGFloat dy = location.y - start.y;
CGFloat magnitude = sqrt(dx*dx+dy*dy);
if (magnitude >= kMinDistance) {
// Determine time difference from start of the gesture
CGFloat dt = touch.timestamp - startTime;
if (dt > kMinDuration) {
// Determine gesture speed in points/sec
CGFloat speed = magnitude / dt;
if (speed >= kMinSpeed && speed <= kMaxSpeed) {
// Calculate normalized direction of the swipe
dx = dx / magnitude;
dy = dy / magnitude;
NSLog(@"Swipe detected with speed = %g and direction (%g, %g)",speed, dx, dy);
}
}
}
}
这篇关于精灵套件 - 确定滑动精灵的滑动手势矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!