滑动手势从另一个类调用方法

时间:2014-03-13 12:32:24

标签: ios objective-c sprite-kit

我努力让这个工作起来。 我有一个名为playerNode的SKSpriteNode类,我想用滑动手势移动它。我试图从视图控制器调用滑动句柄方法,但我没有得到任何响应。

ViewController.h

#import <UIKit/UIKit.h>
#import <SpriteKit/SpriteKit.h>

@interface ViewController : UIViewController
@property (nonatomic, strong) UISwipeGestureRecognizer *leftSwipeGestureRecognizer;
@property (nonatomic, strong) UISwipeGestureRecognizer *rightSwipeGestureRecognizer;
@end

ViewController.m

#import "ViewController.h"
#import "MyScene.h"
#import "playerNode.h"

@implementation ViewController{
    playerNode *player;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Configure the view.
    SKView * skView = (SKView *)self.view;
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;

    // Create and configure the scene.
    SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;

    // Present the scene.
    [skView presentScene:scene];

    // swipe gestures
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:player action:@selector(handleSwipes:)];
    self.rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:player action:@selector(handleSwipes:)];
    self.leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    self.rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:self.leftSwipeGestureRecognizer];
    [self.view addGestureRecognizer:self.rightSwipeGestureRecognizer];

}

playerNode.h

#import <SpriteKit/SpriteKit.h>

@interface playerNode : SKSpriteNode

-(void)handleSwipes:(UISwipeGestureRecognizer *)sender;

@end

playerNode.m

#import "playerNode.h"

@implementation playerNode

-(void)handleSwipes:(UISwipeGestureRecognizer *)sender
{
    NSLog(@"swipe");
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        NSLog(@"left");
    }


    if (sender.direction == UISwipeGestureRecognizerDirectionRight)
    {
        NSLog(@"rigth");
    }
}


@end

我感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:1)

在.h文件中,让玩家对所有人都可见

@property (strong) playerNode *player;

在.m文件中,将播放器设置为目标..

self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self.player action:@selector(handleSwipes:)];

注意:在添加目标之前,我们已经创建了playerNode

答案 1 :(得分:0)

将滑动手势添加到SKScene中。

- (void)didMoveToView: (SKView *)
{
    self.leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] init];
    [self.leftSwipeGestureRecognizer addTarget:self action:@selector(handleSwipes:)];
    [self.leftSwipeGestureRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer: self.leftSwipeGestureRecognizer];
}

didMoveToView或多或少是SpriteKit中的viewDidLoad

然后处理SKScene子类中的滑动