我正在使用AVFoundation来抓取实时相机输入,将像素处理成alpha蒙版图像,然后尝试使用该图像在我的SKView中创建碰撞边界。球将从该节点的边界反弹。一种增强现实的东西。
所有的AVFoundation工作都很好。这是我遇到问题的碰撞。由于设置SKTexture很昂贵,我选择了SKMutableTexture来更新物理体。我似乎无法让它工作(没有发生碰撞),但是使用带有静态图像的SKTexture效果很好。例如,我在代码的其他地方有一个树节点(一个不规则的形状来反弹球),我将其作为开发步骤编写。球从它弹回来很好,但它们不会从我的实时视频节点反弹。 SKTexture / SKMutableTexture和SKPhysicsBody对象在两个节点之间是不同的,并且以不同方式创建。
树示例简单并创建了带有图像的SKPhysicsBody:
SKTexture *objTexture = [SKTexture textureWithImageNamed:objImageName];
self.obj.physicsBody = [SKPhysicsBody bodyWithTexture:objTexture size:self.obj.size];
实时视频节点(self.env)在SKScene中设置如下:
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.dots = [@[]mutableCopy];
self.physicsWorld.contactDelegate = self;
self.physicsWorld.gravity = CGVectorMake(0.0f, 0.0f);
SKPhysicsBody* borderBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsBody = borderBody;
self.physicsBody.friction = 0.0f;
self.env = [[SKSpriteNode alloc]init];
self.env.name = @"env";
self.env.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
self.env.size = self.size;
[self addChild:self.env];
}
}
当处理新的视频帧时,AVFoundationDelegate会调用此方法。
-(void)updateTextureWithPixels:(uint8_t*)pixel length:(size_t)size{
if(self.envTexture == nil){
self.envTexture = [SKMutableTexture mutableTextureWithSize:self.env.size];
self.env.physicsBody = [SKPhysicsBody bodyWithTexture:self.envTexture alphaThreshold:0.5 size:self.env.size];
self.env.physicsBody.friction = 0.0f;
self.env.physicsBody.restitution = 1.0f;
self.env.physicsBody.linearDamping = 0.0f;
self.env.physicsBody.allowsRotation = NO;
self.env.physicsBody.dynamic = NO;
}
[self.envTexture modifyPixelDataWithBlock:^(void *pixelData, size_t lengthInBytes) {
pixelData = pixel;
NSLog(@"updated texture");
}];
}
添加球
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch* touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
self.startPoint = touchLocation;
self.ball = [SKSpriteNode spriteNodeWithImageNamed: @"ball.png"];
self.ball.name = ballCategoryName;
self.ball.position = self.startPoint;
[self.dots addObject:self.ball];
[self addChild:self.ball];
self.ball.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.ball.frame.size.width/2];
self.ball.physicsBody.friction = 0.0f;
self.ball.physicsBody.restitution = 1.0f;
self.ball.physicsBody.linearDamping = 0.0f;
self.ball.physicsBody.allowsRotation = NO;
}
我已经验证了传递给updateTexture的像素是必需的。它们是BGRA格式。一组这些BGRA将全部为0x00或全部为0xFF,由我的AVFoundation类处理。我无法让这种可变纹理做任何事情。我真的希望我只是俯瞰一个小小的环境。
如果您想查看更多代码,请与我们联系。