我似乎在获取物理位置的位置时遇到了一些问题。
我想将一个physicsBody(bodyA)的位置设置为另一个physicsBody(bodyB)的位置,当它与第三个物理碰撞时。
我尝试使用_bodyA.position = _bodyB.position;
,但这不起作用。
问题是,物理学我想要获得的位置一直在四处移动。所以我可能需要一个方法来检查每个帧中physicsBody的位置,当physicsBody发生碰撞时,该方法返回CGPoint。
这可能是一项简单的任务,但我无法弄明白。谢谢你的帮助!
答案 0 :(得分:1)
我做了一个快速的示例项目供您查看。您可以微调代码以满足您的确切需求,但它会告诉您如何做您所要求的。
点按屏幕上的任意位置,将蓝色方块投入红色方块。一旦两者接触,绿色方块的位置将变为红色方块。
我编写代码的另一种方法是将sprite添加到数组中,但这一切都取决于代码的设置方式。
旁注 - 您无法在didBeginContact:
部分更新精灵的位置,因为它不起作用。这就是为什么我在update:
以下是代码:
#import "MyScene.h"
typedef NS_OPTIONS(uint32_t, CNPhysicsCategory)
{
Category1 = 1 << 0,
Category2 = 1 << 1,
Category3 = 1 << 2,
};
@interface MyScene()<SKPhysicsContactDelegate>
@end
@implementation MyScene
{
SKSpriteNode *objectA;
SKSpriteNode *objectB;
SKSpriteNode *objectC;
CGPoint newPositionForObjectC;
}
-(id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
self.physicsWorld.contactDelegate = self;
objectA = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(30, 30)];
objectA.position = CGPointMake(110, 20);
objectA.name = @"objectA";
objectA.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectA.size];
objectA.physicsBody.categoryBitMask = Category1;
objectA.physicsBody.collisionBitMask = Category2;
objectA.physicsBody.contactTestBitMask = Category2;
objectA.physicsBody.affectedByGravity = NO;
[self addChild:objectA];
objectB = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(30, 30)];
objectB.position = CGPointMake(100, 200);
objectB.name = @"objectB";
objectB.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectB.size];
objectB.physicsBody.categoryBitMask = Category2;
objectB.physicsBody.collisionBitMask = Category1;
objectB.physicsBody.contactTestBitMask = Category1;
objectB.physicsBody.affectedByGravity = NO;
[self addChild:objectB];
objectC = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(30, 30)];
objectC.position = CGPointMake(250, 250);
objectC.name = @"objectC";
objectC.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:objectC.size];
objectC.physicsBody.categoryBitMask = Category3;
objectC.physicsBody.collisionBitMask = 0;
objectC.physicsBody.contactTestBitMask = 0;
objectC.physicsBody.affectedByGravity = NO;
[self addChild:objectC];
newPositionForObjectC = CGPointMake(0, 0);
}
return self;
}
- (void)didBeginContact:(SKPhysicsContact *)contact
{
uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
if (collision == (Category1 | Category2))
{
newPositionForObjectC = CGPointMake(contact.bodyA.node.position.x, contact.bodyA.node.position.y);
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[objectA.physicsBody applyImpulse:CGVectorMake(0, 5)];
}
-(void)update:(CFTimeInterval)currentTime
{
if(newPositionForObjectC.x > 0)
{
objectC.position = newPositionForObjectC;
newPositionForObjectC = CGPointMake(0, 0);
}
}
@end