按住按钮时拍摄弹丸

时间:2015-02-02 14:03:29

标签: objective-c sprite-kit

我在游戏中想要做的是在拍摄按钮时不断射击射弹。我一直在使用的是一个简单的touchesBegan和touchesMoved(它只是调用touchesBegan)解决方案。所以我遇到的问题是:如果按住按钮,你只能拍摄一次,但是如果你按住它移动触摸点(调用touchesMoved方法),你将会一次拍摄多个射弹。

我需要帮助的是:如何在按住按钮的同时不断拍摄这些射弹,就像你采用Touch Down方法一样?希望我所要求的是可能的。

1 个答案:

答案 0 :(得分:0)

您可以使用touchesBegantouchesEnded功能来跟踪按下按钮的时间。然后使用update的{​​{1}}函数延迟射击射弹。

逻辑是在按下按钮时将布尔SKScene设置为true。 shooting内的shooting设置为false。这样我们就可以跟踪触摸。然后在touchesEnded函数中,如果update变量为真,则射击射弹。

目标C

shooting

在Swift中

//GameScene.h

@property (nonatomic,strong) SKSpriteNode *shootButton;

//GameScene.m

BOOL shooting = false;
CFTimeInterval lastShootingTime = 0;
CFTimeInterval delayBetweenShots = 0.5;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    if  ([self nodeAtPoint:location] == self.shootButton)
    {
        shooting = true;
        NSLog(@"start shooting");
    }

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    if  ([self nodeAtPoint:location] == self.shootButton)
    {
        shooting = false;
        NSLog(@"stop shooting");
    }
}


-(void)shoot
{
    // Projectile code
    NSLog(@"shooting");
}

-(void)update:(NSTimeInterval)currentTime {

    if (shooting)
    {
        NSTimeInterval delay = currentTime - lastShootingTime;
        if (delay >= delayBetweenShots) {
            [self shoot];
            lastShootingTime = currentTime;
        }
    }
}

您可以调整var shootButton : SKSpriteNode! var shooting = false var lastShootingTime : CFTimeInterval = 0 var delayBetweenShots : CFTimeInterval = 0.5 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { let touch: AnyObject? = touches.anyObject() if let location = touch?.locationInNode(self) { if self.nodeAtPoint(location) == shootButton { self.shooting = true println("start shooting") } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { let touch: AnyObject? = touches.anyObject() if let location = touch?.locationInNode(self) { if self.nodeAtPoint(location) == shootButton { self.shooting = false println("stop shooting") } } } func shoot() { // Projectile code println("shooting") } override func update(currentTime: NSTimeInterval) { if shooting { let delay = currentTime - lastShootingTime if delay >= delayBetweenShots { shoot() lastShootingTime = currentTime } } } 变量以更改触发发生的速度。