根据触摸位置拖动SKSpriteNode [英] Drag SKSpriteNode based on touch location

查看:101
本文介绍了根据触摸位置拖动SKSpriteNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在y轴上拖动一个精灵,但是根据触点在节点上的开始位置,使精灵粘住到用户手指。
精灵当前正在拖动,但似乎是将精灵的锚点捕捉到节点内的触摸位置

I am trying to drag a sprite in the y axis but make the sprite "stick" to the users finger depending on where the touches began on the node. The sprite is currently dragging but it seems to be snapping the anchorpoint of the sprite to the touch location within the node.

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

Im assuming it has something to do with getting the location within the node by doing [touch locationInNode:selectedNode]; but I am unsure where to go from there.

这是我目前的代码。

-(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。

You need to offset the newPosition based on the current touch position on the node.

-(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;
        }
    }
}

这篇关于根据触摸位置拖动SKSpriteNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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