我遇到的问题是,在发布之前启动了触摸/点击时,仍会在已发布的对象上调用touchesEnded(在iOS上)或mouseUp(在macOS上)。此行为导致我的项目崩溃。我使用SceneKit和SpriteKit叠加层制作了一个精简程序,但我不确定我做错了什么。
我已经开始使用SceneKit游戏模板(iOS或macOS),并且我添加了两个类:
在GameViewController.m结束时 - (void)awakeFromNib我添加了这个:
OverlayScene *overlay=[OverlayScene sceneWithSize:self.gameView.frame.size];// init the overlay
[overlay setupButtons];// create a small GUI menu
[self.gameView setOverlaySKScene:overlay];// add the overlay to the SceneKit view
然后是两个班 OverlayScene.m:
#import <SpriteKit/SpriteKit.h>
#import "Button.h"
@interface OverlayScene : SKScene
-(void)setupButtons;
@end
OverlayScene.m:
#import "OverlayScene.h"
@implementation OverlayScene
-(void)setupButtons{//showing a menu mockup
NSLog(@"setupButtons");
srand((unsigned)time(NULL));// seed the RNG
[self removeAllChildren];//remove all GUI element (only one button or nothing (in the first call)
Button *b=[[Button alloc] initWithSelector:@selector(setupButtons) onObject:self];// a new button
b.position=CGPointMake(rand()%300, rand()%300);// just a random position so we can see the change
[self addChild:b];// finally attach the button to the scene
}
@end
Button.h:
#import <SpriteKit/SpriteKit.h>
@interface Button : SKSpriteNode{
SEL selector;//the method which is supposed to be called by the button
__weak id selectorObj;//the object on which the selector is called
}
-(id)initWithSelector:(SEL)s onObject:(__weak id)o;
@end
Button.m:
#import "Button.h"
@implementation Button
-(id)initWithSelector:(SEL)s onObject:(__weak id)o{
//self=[super initWithColor:[UIColor purpleColor] size:CGSizeMake(200, 60)];//this is the code for iOS
self=[super initWithColor:[NSColor purpleColor] size:CGSizeMake(200, 60)];// this is for macOS
selector=s;//keep the selector with the button
selectorObj=o;
[self setUserInteractionEnabled:YES];//enable touch handling
return self;
}
//-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{//called on iOS
-(void)mouseDown:(NSEvent *)event{//called on macOS
[selectorObj performSelector:selector];//we are calling the method which was given during the button initialization
}
@end
当您单击按钮时,它会按预期移除(并由弧释放)并创建一个新按钮。只要按住鼠标按钮,一切都很好。当您释放它时,应用程序崩溃,因为mouseUp事件被发送到已删除的按钮: