我可以移动整个物体吗?

问题描述 投票:0回答:1

我用多维数组创建了对象。

当我试图移动最终的物体时,最后一块是移动的。我怎么能完全移动形成的形状?

enter image description here

enter image description here

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch: AnyObject in touches{

            let location = touch.location(in: self)
            square.position.x = location.x
            square.position.y = location.y
    }
}

移动代码:

我用下面的代码在屏幕上打印它们:

for row in 0..<t.bitmap.count {
        for col in 0..<t.bitmap[row].count {
            if t.bitmap[row][col] > 0 {
                let block = t.bitmap[row][col]

                square = SKSpriteNode(color: colors[block], size: CGSize(width: blockSize, height: blockSize))
                square.anchorPoint = CGPoint(x: 1.0, y: 0)
                square.position = CGPoint(x: col * Int(blockSize) + col, y: -row * Int(blockSize) + -row)
                square.position.x += location.x
                square.position.y += location.y
                self.addChild(square)

            }
        }
    }
swift xcode sprite-kit swift4
1个回答
0
投票

目前还不清楚你究竟在问什么,大图像和缺失的代码没有帮助。但是,您似乎移动了一个块:

square.position.x = location.x
square.position.y = location.y

并且您希望以相同的相对量移动所有块。您可以通过以下两行来实现这一点,首先计算每个方向的相对数量:

let deltaX = location.x - square.position.x
let deltaY = location.y - square.position.y

然后调用一个函数来移动所有块:

 moveAllBlocks(deltaX, deltaY)

此例程需要通过添加增量来迭代更新其position的所有块。

HTH


附录

回应评论

我说英语不好,抱歉。例子没有解决问题。是的,我想移动所有块。

让我们尝试一些示例值,看看是否有帮助,这将是伪代码 - 您需要了解算法,然后在您的代码中实现。

假设您有一个8x8网格和多个图块,每个图块都作为一个位置(行,列)。我们将考虑当前处于(2,3)的一个区块。

触摸事件告诉您将此图块移动到(例如)(5,1)。您目前通过分配磁贴位置来实现移动:

tile.location = (5, 1)

然后面临移动其他瓷砖的位置的问题,使它们与您移动的瓷砖保持相同的相对位置。

解决方案是先找出移动第一个图块的相对距离,而不是仅仅分配其新的绝对位置,我们通过获取新旧位置之间的差异来做到这一点:

delta = newLocation - tile.location
      = (2, 3) - (5, 1)
      = (3, -2)

现在你有相对数量(3,-2)来移动平铺,你可以将所有平铺移动相同的相对数量,它们将保持相同的关系。要做到这一点,你迭代(循环)所有的瓷砖,用增量金额(3,-2)改变每个瓷砖的位置,即你在行中加3,从列中减去2。

© www.soinside.com 2019 - 2024. All rights reserved.