在我简单的射箭游戏中,我定义了一个箭头节点和一个带有相关物理实体的目标节点。
当我尝试使用SKPhysicsJointFixed(我也尝试过其他类型)将它们连接在一起时,在实际命中目标节点之前看似在随机点创建的关节的行为是不准确的。
我使用了摩擦和恢复值以及SKShapeNode(带有CGPath)和SKSpriteNode(在精灵周围有一个矩形)来定义目标,但两者都出现问题。
当仅使用碰撞时,箭头会从目标的正确位置反弹,这似乎没问题。只有当连接发生时,结果才会在屏幕上随机出现,通常距离目标节点“表面”10-20个点。
static const uint32_t arrowCategory = 0x1 << 1;
static const uint32_t targetCategory = 0x1 << 2;
- (SKSpriteNode *)createArrowNode
{
SKSpriteNode *arrow = [[SKSpriteNode alloc] initWithImageNamed:@"Arrow.png"];
arrow.position = CGPointMake(165, 110);
arrow.name = @"arrowNode";
arrow.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:arrow.frame.size];
arrow.physicsBody.angularVelocity = -0.25;
arrow.physicsBody.usesPreciseCollisionDetection = YES;
arrow.physicsBody.restitution = 0.0;
arrow.physicsBody.friction = 0.0;
arrow.physicsBody.categoryBitMask = arrowCategory;
arrow.physicsBody.collisionBitMask = targetCategory;
arrow.physicsBody.contactTestBitMask = /*arrowCategory | */targetCategory | bullseyeCategory;
return arrow;
}
-void(createTargetNode)
{
SKSpriteNode *sprite = [[SKSpriteNode alloc] initWithImageNamed:@"TargetOutline.png"];
sprite.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:sprite.size];
sprite.position = CGPointMake(610, 100);
sprite.name = @"targetNode";
sprite.physicsBody.usesPreciseCollisionDetection = NO;
// sprite.physicsBody.affectedByGravity = NO;
// sprite.physicsBody.mass = 20000;
sprite.physicsBody.dynamic = NO;
sprite.physicsBody.friction = 0.0;
sprite.physicsBody.restitution = 0.0;
sprite.physicsBody.categoryBitMask = targetCategory;
sprite.physicsBody.contactTestBitMask = targetCategory | arrowCategory;
[self addChild:sprite];
}
- (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 & arrowCategory) != 0 &&
(secondBody.categoryBitMask & targetCategory) != 0)
{
CGPoint contactPoint = contact.contactPoint;
NSLog(@"contactPoint is %@", NSStringFromCGPoint(contactPoint));
float contact_x = contactPoint.x;
float contact_y = contactPoint.y;
SKPhysicsJoint *joint = [SKPhysicsJointFixed jointWithBodyA:firstBody bodyB:secondBody anchor:(CGPoint)contactPoint ];
[self.physicsWorld addJoint:joint];
CGPoint bullseye = CGPointMake(590, 102.5);
NSLog(@"Center is %@", NSStringFromCGPoint(bullseye));
CGFloat distance = SDistanceBetweenPoints(contactPoint, bullseye);
NSLog(@"Distance to bullseye is %f", distance);
}