ios - touchesMoved 在特定的移动对象上

标签 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]];
    }

我的问题是,如果我触摸它,该对象会移动几个像素,但之后会立即停止。我怎样才能让它用我的手指移动,如果我放开它,它会像之前编程的那样继续向左移动?谢谢!!

最佳答案

所以这里的诀窍是在 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));
    }
...
}

关于ios - touchesMoved 在特定的移动对象上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22668258/

相关文章:

iOS - 在 UIView 中检测触摸?

ios - UITextField Xcode 的圆角

ios - 使用 SpriteKit 进行地址 sanitizer

iphone - iOS 可以批量发送短信吗?

swift - 如何打造门户效果? Swift/Spritekit

python - Xcode:通过 LLDB 脚本或其他方式显示 Apple 框架类的属性

ios - 无法在 iOS 的 viewController 中调用 touchesBegan/touchesMoved 方法

ios - 适用于 iOS 7、6、5 的触摸控件...但不适用于 iOS 8

ios - 从 UIViewController 更改 UIWindow backgroundColor?

ios - 预定的 NSNotification(而不是 UILocalNotification)... Swift 解决方案?