【问题标题】:Spritekit PhysicsBody and Sprite don't line upSpritekit PhysicsBody 和 Sprite 不对齐
【发布时间】:2014-05-22 15:41:39
【问题描述】:

我正在开发一个游戏,用户可以画一条线,一个球会从上面弹开,但我遇到了一个问题,即线和物理体不对齐。这显然是一个破坏游戏的问题。

- (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;

}

提前致谢!

【问题讨论】:

    标签: sprite-kit cgpath skphysicsbody


    【解决方案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。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多