user3339697
user3339697

Reputation:

Spritekit PhysicsBody and Sprite don't line up

I am working on a game where the user can draw a line and a ball will bounce off of it but I have run into a problem where the line and the physics body don't line up. This is obviously a game breaking issue.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

// Removes previous line
[lineNode removeFromParent];
CGPathRelease(pathToDraw);


UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];

pos1x = positionInScene.x;
pos1y = positionInScene.y;
NSLog(@"%d, %d", pos1x, pos1y);
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Removes previous line
[lineNode removeFromParent];
line.physicsBody = nil;



UITouch* touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];

pathToDraw = CGPathCreateMutable();
CGPathMoveToPoint(pathToDraw, NULL, pos1x, pos1y);

lineNode = [SKShapeNode node];
lineNode.path = pathToDraw;
lineNode.strokeColor = [SKColor blackColor];
[self addChild:lineNode];

CGPathAddLineToPoint(pathToDraw, NULL, positionInScene.x, positionInScene.y);
lineNode.path = pathToDraw;

int pos2x = positionInScene.x;
int pos2y = positionInScene.y;


SKSpriteNode* line = [[SKSpriteNode alloc] init];
line.name = lineCategoryName;
line.position = CGPointMake(pos1x, pos1y);
[self addChild:line];
line.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(pos1x, pos1y) toPoint:CGPointMake(pos2x, pos2y)];
line.physicsBody.restitution = 0.1f;
line.physicsBody.friction = 0.4f;
// make physicsBody static
line.physicsBody.dynamic = NO;

}

You see the line (in black) and the PhysicsBody (in green)

Thanks in advance!

Upvotes: 2

Views: 285

Answers (1)

sangony
sangony

Reputation: 11696

Modify your code line:

line.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(pos1x, pos1y) toPoint:CGPointMake(pos2x, pos2y)];

to this:

line.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(0, 0) toPoint:CGPointMake(pos2x-line.position.x, pos2y-line.position.y)];

Your problem is that you are not taking into account that the line physical body's coordinates are relative to the view coordinates.

The documentation for bodyWithEdgeFromPoint:toPoint: clearly states that:

Parameters p1 The starting point for the edge, relative to the owning node’s origin. p2 The ending point for the edge, relative to the owning node’s origin.

In other words if your line starts at the screen coordinates of 30,30 and ends at 50,35 that translates to your physics body starting coordinates are 0,0 and ending coordinates are 20,5.

Upvotes: 1

Related Questions