Spritekit 在触摸时旋转节点 [英] Spritekit rotate a node while touching

查看:44
本文介绍了Spritekit 在触摸时旋转节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您愿意,我目前正在研究某种自上而下的赛车.这个想法是有两个按钮,每个按钮用于向左或向右转动汽车.这一切都有效,但只能轻轻一按.我想让玩家只需按住按钮就可以转动汽车.我现在有

I'm currently working on some sort of top down racer if you will. The idea is to have two buttons, each for turning a car left or right. This all works, but it only works with one touch. I'd like to have the player turn the car by simply holding down the button. I now have

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

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

        if ([node.name isEqualToString:@"buttonLeft"]) {
            while (touched == YES) {
                playerRotate = player.zRotation;
                playerRotate += playerAngle;
            }
        }
    }
}

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
    player.zRotation = playerRotate;
    float dx = playerSpeed * cos(player.zRotation);
    float dy = playerSpeed * sin(player.zRotation);
    player.physicsBody.velocity = CGVectorMake(dx, dy);
}

玩家汽车的速度在更新函数中更新.并且在touchesEnded touch 中设置为NO.问题是这个while循环卡住了(我的手机不再处理任何触摸),但我不知道只要按下按钮就没有其他方法可以保持旋转汽车.如果我删除 while 循环,代码就可以工作.任何帮助表示赞赏!

The velocity of the players car is updated in the update function. And in touchesEnded touched is set to NO. The problem is that this while loop gets stuck (and my phone does not proces any touches anymore), but I know no other way to keep rotating the car as long as the button is pressed. The code works if I remove the while loop. Any help is appreciated!

推荐答案

您已经有了正确的想法.而不是将您的 BOOL 设置为所有触摸的通用 YES.创建一个 touchLeft 和 touchRight BOOL.

You already have the right idea. Instead of setting your BOOL touched to a generic YES for all touches. Create a touchLeft and touchRight BOOL.

在您的 if([node.name isEqualToString:@"buttonLeft"]) 之后,将 touchLeft BOOL 设置为 YES.创建一个 if([node.name isEqualToString:@"buttonRight"]) 并设置 touchRight BOOL.

After your if([node.name isEqualToString:@"buttonLeft"]) set the touchLeft BOOL to YES. Create a if([node.name isEqualToString:@"buttonRight"]) and set the touchRight BOOL.

在您的更新方法中,您可以检查 BOOL YES 值并相应地应用代码.

In your update method you can then check for either BOOL YES value and apply code accordingly.

请记住,您还需要为 touchesEnded 创建相同的代码逻辑,以便在不再存在触摸时将两个 BOOL 设置回 NO.

Remember you also need to create the same code logic for touchesEnded in order to set both BOOL back to NO once a touch is no longer present.

这篇关于Spritekit 在触摸时旋转节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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