我试图为iOS制作一个非常简单的SpriteKit应用,但是存在问题:
#import "MyScene.h"
static const uint32_t laserCategory = 0x1 << 0;
static const uint32_t enemyCategory = 0x1 << 0;
@implementation MyScene
- (id) initWithSize: (CGSize) size
{
if (self = [super initWithSize: size])
{
self.backgroundColor = [SKColor colorWithRed: 1.0 green: 1.0 blue: 1.0 alpha: 1.0];
self.physicsWorld.gravity = CGVectorMake(0,0);
SKSpriteNode *ship = [SKSpriteNode spriteNodeWithImageNamed: @"Ship"];
ship.position = CGPointMake (CGRectGetMidX (self.frame), 50);
[self addChild: ship];
SKSpriteNode *enemy = [SKSpriteNode spriteNodeWithImageNamed: @"Enemy"];
enemy.position = CGPointMake (CGRectGetMidX (self.frame), 440);
[self addChild: enemy];
enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: enemy.size];
enemy.physicsBody.dynamic = YES;
enemy.physicsBody.categoryBitMask = enemyCategory;
enemy.physicsBody.contactTestBitMask = laserCategory;
enemy.physicsBody.collisionBitMask = 0;
SKAction *moveEnemy = [SKAction moveByX: 0.0 y: -500.0 duration: 5.0];
[enemy runAction: moveEnemy];
} return self;
}
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event
{
SKSpriteNode *laser = [SKSpriteNode spriteNodeWithImageNamed: @"Laser"];
laser.position = CGPointMake (CGRectGetMidX (self.frame), 100);
[self addChild: laser];
laser.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize: laser.size];
laser.physicsBody.dynamic = YES;
laser.physicsBody.categoryBitMask = laserCategory;
laser.physicsBody.contactTestBitMask = enemyCategory;
laser.physicsBody.collisionBitMask = 0;
SKAction *moveLaser = [SKAction moveByX: 0.0 y: 2000.0 duration: 5.0];
[laser runAction: moveLaser];
}
- (void) laser: (SKSpriteNode *) laser didCollideWithEnemy: (SKSpriteNode *) enemy
{
[laser removeFromParent];
[enemy removeFromParent];
}
- (void) didBeginContact: (SKPhysicsContact *) contact
{
SKPhysicsBody *firstBody, *secondBody;
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
{
firstBody = contact.bodyA;
secondBody = contact.bodyB;
}
else
{
firstBody = contact.bodyB;
secondBody = contact.bodyA;
}
if ((firstBody.categoryBitMask & laserCategory) != 0 && (secondBody.categoryBitMask & enemyCategory) != 0)
{
[self laser: (SKSpriteNode *) firstBody.node didCollideWithEnemy: (SKSpriteNode *) secondBody.node];
}
}
@end
这是我的&#34; MyScene.m&#34;文件,一切正常。唯一不起作用的是激光对象和敌方物体之间的碰撞检测。他们只是穿过对方。有解决方案吗欢迎任何其他提示。
感谢。
答案 0 :(得分:2)
您为两个不同的类别设置了相同的位掩码:
static const uint32_t laserCategory = 0x1 << 0;
static const uint32_t enemyCategory = 0x1 << 0;
之后,didBeginContact:方法中的if语句错误:
if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
你应该将其中一个更改为0x1&lt;&lt; 1:
static const uint32_t laserCategory = 0x1 << 0;
static const uint32_t enemyCategory = 0x1 << 1;
//扩展
您还缺少设置联系委托给phasic世界,在initWithSize中设置重力后添加此代码:
self.physicsWorld.gravity = CGVectorMake(0,0);
self.physicsWorld.contactDelegate = self;
我假设您向MyScene类添加了委托声明:
<SKPhysicsContactDelegate>