ios - 根据触摸位置拖动 SKSpriteNode

标签 ios objective-c sprite-kit

我试图在 y 轴上拖动 Sprite ,但根据节点上开始触摸的位置,使 Sprite “粘附”到用户的手指上。 Sprite 目前正在拖动,但它似乎正在将 Sprite 的 anchor 捕捉到节点内的触摸位置

我假设它与通过执行 [touch locationInNode:selectedNode]; 获取节点内的位置有关,但我不确定从那里去哪里。

这是我当前的代码。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    for (UITouch *touch in touches) {
        CGPoint location  = [touch locationInNode:self];
        SKNode *node = [self nodeAtPoint:location];
        CGPoint newPosition = CGPointMake(node.position.x, location.y);

        if ([node.name isEqualToString:self.selectedNode] ) {

            if (newPosition.y > 230) {
                newPosition.y = 230;
            }
            node.position = newPosition;
        }
    }
}

最佳答案

您需要根据节点上的当前触摸位置来偏移newPosition。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    for (UITouch *touch in touches) 
    {
        CGPoint location  = [touch locationInNode:self];
        SKNode *node = [self nodeAtPoint:location];


        if ([node.name isEqualToString:self.selectedNode] )
        {
            CGPoint previousLocation = [touch previousLocationInNode:self];
            float diff = location.y - previousLocation.y;
            CGPoint newPosition = CGPointMake(node.position.x, node.position.y + diff);


            if (newPosition.y > 230) {
                newPosition.y = 230;
            }
            node.position = newPosition;
        }
    }
}

关于ios - 根据触摸位置拖动 SKSpriteNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23436988/

相关文章:

ios - 使用空格进行 GET 查询

ios导航堆栈操作

swift - 如何在 SKScene 中呈现 View Controller ?

swift - 如何在 SpriteKit 的不同类中访问已更改的属性

ios - Sprite Kit,抑制速度较慢的iPhone的质量

ios - 从 iOS 锁定屏幕在应用程序中自定义远程事件处理

iphone - S3PutObjectRequest 在取消之前的 putObjectRequest 后上传失败

ios - 计算字典对象中值的数量

iphone - Xcode 3.2.4 分析器跳过了这个文件?

ios - 对话框打开时如何识别模态对话框外的点击手势