objective c - Global key handler for SpriteKit Game -


i have of key press code in various skscene classes. want happen every time key pressed. key needs re-triggered perform action again. i'm using boolean array keep track of this. may not optimal, it's thought of @ time. looking create class manage of this, key event methods keyup , keydown created in skscene classes. there global way handle keys presses don't have recreate code in every scene in game?

you can subclass skview , perform key press handling in centralized location. approach has several benefits: 1. since key press logic in single class, changes logic made class instead of in of scenes , 2) removes device-specific input logic multiple scenes. if decide port app ios, example, can change interface keyboard/mouse touches in single file.

the following implementation of key press handler in custom subclass of skview. uses protocol/delegate design pattern send key press messages various scenes. delegation convenient way object (in case class) communication other classes , protocol defines how communication take place.

  1. create subclass of skview

customskview.h

@protocol keypresseddelegate;  @interface customskview : skview  @property (weak) id <keypresseddelegate> delegate;  @end  @protocol keypresseddelegate  - (void) uparrowpressed; - (void) downarrowpressed;  @end 

customskview.m

all key press handling logic resides here. details of how key presses handled hidden code acts on key presses.

@implementation customskview:skview {     // add instance variables here }  // called when view created. - (id) initwithcoder:(nscoder *)coder {     self = [super initwithcoder:coder];     if (self) {         // allocate , initialize instance variables here      }     return self; }  - (void) keydown:(nsevent *)theevent {     // add code handle key down event here     if (self.delegate) {         switch (theevent.keycode) {             case 126:                 [self.delegate uparrowpressed];                 break;             case 125:                 [self.delegate downarrowpressed];                 break;             default:                 break;         }     } }  @end 
  1. adopt protocol

gamescene.h

#import "customskview.h"  @interface gamescene : skscene <keypresseddelegate>  @end 
  1. implement delegate method in scenes require key press info

gamescene.m

@implementation gamescene  -(void)didmovetoview:(skview *)view {     ((customskview *)view).delegate = self; }  - (void) uparrowpressed {     nslog(@"up arrow pressed"); } - (void) downarrowpressed {     nslog(@"down arrow pressed"); }  @end 
  1. in main .xib file, set class skview custom class:

enter image description here

enter image description here


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -