touchesMoved在特定的移动对象上

时间:2014-03-26 17:09:10

标签: ios sprite-kit touchesmoved

我正在使用Spritekit为iOS 7创建游戏。游戏中的圆圈使用此代码在屏幕上移动

_enemy = [SKSpriteNode spriteNodeWithImageNamed:@"greeny"];
        _enemy.position = CGPointMake(CGRectGetMidX(self.frame)+300,
                                      CGRectGetMidY(self.frame));
_enemy.size = CGSizeMake(70, 70);
_enemy.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:35];
_enemy.physicsBody.mass = 0;

_enemy.physicsBody.categoryBitMask = Collisiongreen;
[_enemies addObject:_enemy];
NSLog(@"Enemies%lu",(unsigned long)_enemies.count);

[self addChild:_enemy];
[_enemy runAction:[SKAction moveByX:-900 y:0 duration:4]];
[self runAction:[SKAction playSoundFileNamed:@"Spawn.wav" waitForCompletion:NO]];
[self runAction:[SKAction sequence:@[
                                  [SKAction waitForDuration:1.4],
                                  [SKAction performSelector:@selector(move)
                                                   onTarget:self],
                                     ]]];

我想知道,当用户触摸屏幕上移动的其中一个物体时,他们可以用手指向上或向下移动它(这就是为什么我使用触摸移动) 我现在设置的代码是

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

    if(_dead)
        return;
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    if(CGRectContainsPoint(_enemy.frame, location)){

        [_enemy runAction:[SKAction moveTo:[[touches anyObject] locationInNode:self] duration:0.01]];
    }

我的问题是,如果我触摸它,对象将移动几个像素,但会在之后停止。如何让它用我的手指移动,如果我放手它将继续像以前编程一样向左移动?谢谢!!

1 个答案:

答案 0 :(得分:1)

所以这里的技巧是在touchesMoved方法中,你想要将敌人的位置设置为触摸的位置。使用touchesEnded方法执行一种方法,使敌人继续朝着最后一次触摸的方向前进。这是一个粗略的未经测试的例子。

您需要存储当前位置与之前位置的差异。

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

    if(_dead)
        return;
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    if(CGRectContainsPoint(_enemy.frame, location)){

        someBool = False;
        [_enemy setPosition:location];
        changeInX = location.x - lastX;
        changeInY = location.y - lastY;
        lastX = location.x;
        lastY = location.y;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    someBool = True;
}

- (void)update:(NSTimeInterval)currentTime
{
...
    if (someBool) {
        enemy.position = CGPointMake((enemy.position.x + changeInX), (enemy.position.y + changeInY));
    }
...
}