我正在制作一个游戏,用户可以画一条线,一个球会反弹但是我遇到了线和物理体没有对齐的问题。这显然是一个破坏游戏的问题。
- (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;
}
提前致谢!
答案 0 :(得分:1)
修改您的代码行:
line.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(pos1x, pos1y) toPoint:CGPointMake(pos2x, pos2y)];
到此:
line.physicsBody = [SKPhysicsBody bodyWithEdgeFromPoint:CGPointMake(0, 0) toPoint:CGPointMake(pos2x-line.position.x, pos2y-line.position.y)];
您的问题是您没有考虑线物理实体的坐标相对到视图坐标。
bodyWithEdgeFromPoint:toPoint的文档:明确指出:
参数 P1 边缘的起点,相对到拥有节点的原点。 P2 边缘的终点,相对到拥有节点的原点。
换句话说,如果您的线从屏幕坐标30,30开始并以50,35结束,那么转换为您的物理体,起始坐标为0,0,结束坐标为20,5。