在触摸结束时执行SpriteKit物理身体碰撞/接触

时间:2013-10-05 20:37:34

标签: ios7 sprite-kit

我有一些物理身体节点。 Sprite Kit立即调用didbegincontact方法。我希望在我释放触摸时调用该方法,以便它可以在释放单击时执行操作,而不是立即调用方法导致某些操作设置问题。

- (void)didBeginContact:(SKPhysicsContact *)contact
{   NSLog(@"%hhd", _touching);
    if(_touching == NO)
     return;
something here
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
_touching = YES;
 NSLog(@"%hhd", _touching);

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
_touching = NO;
NSLog(@"%hhd", _touching);
something here
}

1 个答案:

答案 0 :(得分:1)

  1. 设置全局变量,即

    BOOL _touching;
    
  2. 当您触摸/释放(触摸结束并开始)时,您将该var设置为YES / NO;

  3. 在didbegincontact中,使用类似

    的内容
    if(_touching == YES) {
        // what I want to happen when I am touching
    } 
    else {
       // i must not be touching so do this
    }
    
  4. 这是基本的设置 - 不过我认为游戏逻辑就是问题所在,也许会想出一种解决问题的不同方式

    @interface XBLMyScene()
    
    @property (strong, nonatomic) SKNode *world;
    @property (strong, nonatomic) SKSpriteNode *ball;
    @property BOOL touching;
    @end
    
    @implementation XBLMyScene
    
    -(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
    
        self.world = [SKNode node];
        [self addChild:self.world];
    
        self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
    
        self.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointZero toPoint:CGPointMake(500, 0)];
    
        self.ball = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(40, 40)];
        self.ball.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(40, 40)];
        self.ball.position = CGPointMake(200, 300);
        [self.world addChild:self.ball];
    
        self.touching = NO;
    
    }
    return self;
    }
    
    -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        self.touching = YES;
    }
    
    -(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    
        self.touching = NO;
    }
    
    - (void) didSimulatePhysics
    {
    if (self.touching) {
        NSLog(@"I am touching");
    }
    else {
        NSLog(@"I am not touching");
    }
    }