从CGPath保持SKSpriteNode与SKShapeNode的相对位置

时间:2015-10-28 03:33:55

标签: swift sprite-kit cgpath skshapenode

我有一个坐标数组数组(来自shapefile),我正在尝试将其作为一系列SKSpriteNodes。

我的问题是我需要保持数组中每个形状的相对位置。如果我使用SKShapeNodes,它可以工作,因为它们只是直接从我追踪的路径创建,但它们的资源消耗非常高,特别是我不能对它们使用光照效果。

如果我使用带有从形状节点创建的纹理的SKSpriteNodes,那么我将失去它们的相对位置。

我尝试计算每个形状的中心,但它们的位置仍然不准确。

到目前为止我是如何绘制它们的:

override func didMoveToView(view: SKView)
{
    self.backgroundColor = SKColor.blackColor()
    let shapeCoordinates:[[(CGFloat, CGFloat)]] = [[(900.66563867095, 401.330302084953), (880.569690215615, 400.455067051099), (879.599839322167, 408.266821560754), (878.358968429675, 418.182833936104), (899.37522863267, 418.54861454054), (900.66563867095, 401.330302084953)],
        [(879.599839322167, 408.266821560754), (869.991637153925, 408.122907880045), (870.320569111933, 400.161243286459), (868.569953361733, 400.11339198742), (864.517810669155, 399.54973007215), (858.682258706015, 397.619367903278), (855.665753299048, 395.808813873244), (853.479452218432, 392.811211835046), (847.923492419877, 394.273974470316), (834.320860167515, 397.859104108813), (826.495867917475, 399.921507079808), (829.86572598778, 404.531781837208), (835.898936154083, 409.178035013947), (840.887737516875, 411.839958392806), (847.191868005112, 414.441797809335), (854.251943938193, 416.198384209245), (860.095769038325, 417.277496957155), (866.21091316512, 417.954970608037), (873.27118845149, 418.182833936104), (878.358968429675, 418.182833936104), (879.599839322167, 408.266821560754)],
        [(931.018881691707, 402.151689416542), (910.610746904717, 401.600140235583), (910.380693886848, 411.576056681467), (930.79710181083, 411.750012342223), (931.018881691707, 402.151689416542)],
        [(880.569690215615, 400.455067051099), (870.320569111933, 400.161243286459), (869.991637153925, 408.122907880045), (879.599839322167, 408.266821560754), (880.569690215615, 400.455067051099)]]

    for shapeCoord in shapeCoordinates
    {
        let path = CGPathCreateMutable()
        var center:(CGFloat, CGFloat) = (0, 0)

        for i in 0...(shapeCoord.count - 1)
        {
            let x = shapeCoord[i].0
            let y = shapeCoord[i].1
            center.0 += x
            center.1 += y

            if i == 0
            {
                CGPathMoveToPoint(path, nil, x, y)
            }
            else
            {
                CGPathAddLineToPoint(path, nil, x, y)
            }
        }

        center.0 /= CGFloat(shapeCoord.count)
        center.1 /= CGFloat(shapeCoord.count)

        let shape = SKShapeNode(path: path)
        let texture = self.view?.textureFromNode(shape)
        let sprite = SKSpriteNode(texture: texture)
        sprite.position = CGPointMake(center.0, center.1)

        //self.addChild(shape)
        self.addChild(sprite)
    }

}

是否可行或是否应该切换到其他技术/方法?

0 个答案:

没有答案
相关问题