我试图为我的iOS spritekit游戏创建一个盾牌加电,而不是刷新当前的盾牌,它在顶部堆叠另一个盾牌。我的代码:
-(void)didMoveToView:(SKView *)view {
...
self.shieldIsActive = NO;
...
}
-(void)didBeginContact:(SKPhysicsContact *)contact{
...
else if (firstBody.categoryBitMask == CollisionCategoryLaser | firstBody.categoryBitMask == CollisionCategoryPlasmaShot |firstBody.categoryBitMask == CollisionCategoryProjectile && secondBody.categoryBitMask == CollisionCategoryShieldIcon){
// Projectile OR Plasma Shot Or Laser hits Shield Icon
ShieldIconNode *shieldIcon = (ShieldIconNode *)secondBody.node;
ShieldNode *shield = [ShieldNode shieldAtPosition:CGPointMake(CGRectGetMidX(self.frame)+4, CGRectGetMidY(self.frame)-210)];
[shieldIcon removeFromParent];
if (firstBody.categoryBitMask == CollisionCategoryProjectile){
ProjectileNode *projectile = (ProjectileNode *)firstBody.node;
[projectile removeFromParent];
}
if (!self.shieldIsActive){
[self addChild:shield];
self.shieldIsActive = YES;
}
// Remove shield after a period of time. BUG: Adds multiple shields if one is already active
if (self.shieldIsActive){
SKAction *wait = [SKAction waitForDuration:ShieldTimer];
[self runAction:wait completion:^{[shield removeFromParent];}];
self.shieldIsActive = NO;
...
}
答案 0 :(得分:4)
让我们取代这个条件:
else if (firstBody.categoryBitMask == CollisionCategoryLaser | firstBody.categoryBitMask == CollisionCategoryPlasmaShot |firstBody.categoryBitMask == CollisionCategoryProjectile && secondBody.categoryBitMask == CollisionCategoryShieldIcon){
由此:
else if ((firstBody.categoryBitMask == CollisionCategoryLaser || firstBody.categoryBitMask == CollisionCategoryPlasmaShot || firstBody.categoryBitMask == CollisionCategoryProjectile ) && secondBody.categoryBitMask == CollisionCategoryShieldIcon){
请注意,对于OR运算符,使用||
代替|
。
答案 1 :(得分:4)
正如Domsware指出的那样,在第一个|
语句中,需要用逻辑||
(以及添加的相应括号)替换按位if
。奇怪的是,由于|
运算符的优先级低于==
运算符,因此您的if
语句可能已按预期工作。
另外,你应该考虑隐藏/显示盾牌,而不是像Whirlwind建议的那样添加/移除盾牌。
那说了一些想法......
if (!self.shieldIsActive)
和if (self.shieldIsActive)
的条件始终为true
(除非shieldIsActive
设置在代码中的其他位置),这可能会导致多个屏蔽一次一幕self.shieldIsAction = NO
移动到操作的完成块将解决此问题和一些代码......
if (!self.shieldIsActive){
ShieldNode *shield = [ShieldNode shieldAtPosition:CGPointMake(CGRectGetMidX(self.frame)+4, CGRectGetMidY(self.frame)-210)];
[self addChild:shield];
self.shieldIsActive = YES;
SKAction *wait = [SKAction waitForDuration:ShieldTimer];
[self runAction:wait completion:^{
[shield removeFromParent];
self.shieldIsActive = NO;
}];
}