简体   繁体   English

用两个手指移动两个不同的对象SpriteKit

[英]Moving two different objects with two fingers SpriteKit

I want to move two different objects with two fingers . 我想用两个手指移动两个不同的对象。 The problem is that I can't use touchBegan method because of I can't recognize which object I currently operate. 问题是由于无法识别当前正在操作的对象,所以无法使用touchBegan方法。 The best way is to use gesture recognizers because of I can recognize view that I currently dragging, I can move two or more different objects and I always have refference to them. 最好的方法是使用手势识别器,因为我可以识别当前正在拖动的视图,可以移动两个或更多不同的对象,并且始终对它们有所了解。 But I can't use gesture recognizers with SpriteKit.I can't add gestures to my objects but I can add gestures to main SKView , but it will work only with one touch object. 但是我不能在SpriteKit中使用手势识别器,也不能在我的对象中添加手势,但是可以在主SKView中添加手势,但是它仅适用于一个触摸对象。 So, the question is how can i move two different objects with SpriteKit ? 因此,问题是我如何使用SpriteKit移动两个不同的对象?

The touches... methods sure can be used for this. 触摸...方法肯定可以用于此目的。 Just for example, to pan multiple sprites, first iterate over the touches. 仅举例来说,要平移多个精灵,请先遍历触摸。 For each one, ask the scene for all the nodes at that point. 对于每个节点,询问场景中所有节点。 (This is node you can get a reference to your objects) (这是您可以获取对象引用的节点)

Then iterate over all the nodes at that point. 然后在那一点上遍历所有节点。 If they pass some sort of movability test (lets say by name) use arithmetic to determine their new positions based on the current and previous touch locations of the UITouch object. 如果它们通过某种可移动性测试(按名称说),请使用算法根据UITouch对象的当前和以前的触摸位置确定其新位置。 That being said, the code below will move any sprite on your scene with the name "nameOfMovableObject" along with the touch at that location. 话虽如此,下面的代码将移动场景中名称为“ nameOfMovableObject”的所有子画面以及该位置的触摸。

CG_INLINE CGPoint CGPointFromPreviousCoords(CGPoint affectedPoint, CGPoint currentPoint, CGPoint previousPoint) {
    return CGPointMake(affectedPoint.x + currentPoint.x - previousPoint.x, affectedPoint.y + currentPoint.y - previousPoint.y);
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];
        CGPoint previousLocation = [touch previousLocationInNode:self];

        for (SKNode *node in [self nodesAtPoint:location]) {
            if ([node.name isEqualToString:@"nameOfMovableObject"]) {
                [node setPosition:CGPointFromPreviousCoords(node.position, location, previousLocation)];
            }
        }
    }
}

我通过将SKViews添加到-(void)didMoveToView:方法来解决此问题,并向此SKViews添加标准UIGestureRecognizes

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

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