didBeginContact :( SKPhysicsContact *)联系人未被调用 [英] didBeginContact:(SKPhysicsContact *)contact not invoked
问题描述
我创建了 SKScene
继承的类。
问题是关于物理体法的接触
I have created SKScene
inherited class.
Problem is that on contact of physics body method
- (void)didBeginContact:(SKPhysicsContact *)contact
未被调用
解决方案可能很简单,但作为初学者使用精灵工具包我坚持这个。
is not invoked solution may be simple but as beginner with sprite kit i am stuck with this.
以下是代码
#import "MyScene.h"
@interface MyScene ()
@property BOOL contentCreated;
@end
@implementation MyScene
- (id)initWithSize:(CGSize)size {
self = [super initWithSize:size];
if (self) {
self.physicsWorld.contactDelegate = self;
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
}
return self;
}
- (void)didMoveToView:(SKView *)view
{
if (!self.contentCreated) {
[self buildWorld];
self.physicsWorld.contactDelegate = self;
}
}
#pragma mark - World Building
- (void)buildWorld {
NSLog(@"Building the world");
SKSpriteNode * sprite1 = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(100,100)];
sprite1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100,100)];
sprite1.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) +100);
SKSpriteNode * sprite2 = [[SKSpriteNode alloc] initWithColor:[SKColor grayColor] size:CGSizeMake(100,100)];
sprite2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(100,100)];
sprite2.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) - 100);
[self addChild:sprite1];
[self addChild:sprite2];
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
NSLog(@"contact");
}
@end
提前致谢。
推荐答案
来自 SKPhysicsWorld
文档:
From the SKPhysicsWorld
documentation:
当两个物理实体重叠并且其中一个
物理实体具有contactTestBitMask
属性时,会创建一个联系人与
重叠另一个机构的categoryBitMask
属性。
A contact is created when two physics bodies overlap and one of the physics bodies has a
contactTestBitMask
property that overlaps with the other body’scategoryBitMask
property.
你有为物理机构分配一个 categoryBitMask
和一个 contactTestBitMask
。您想首先创建类别:
You have to assign the physics bodies a categoryBitMask
and a contactTestBitMask
. You want to first create your categories:
static const uint32_t sprite1Category = 0x1 << 0;
static const uint32_t sprite2Category = 0x1 << 1;
接下来,分配类别和联系测试位掩码:
Next, assign the category and contact test bit masks:
sprite1.physicsBody.categoryBitMask = sprite1Category;
sprite1.physicsBody.contactTestBitMask = sprite2Category;
sprite2.physicsBody.categoryBitMask = sprite2Category;
sprite2.physicsBody.contactTestBitMask = sprite1Category;
请注意 SKPhysicsBody
文档:
Note from the SKPhysicsBody
documentation:
为了获得最佳性能,只需在联系人掩码中设置您感兴趣的
交互位。
For best performance, only set bits in the contacts mask for interactions you are interested in.
这篇关于didBeginContact :( SKPhysicsContact *)联系人未被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!