swift - 我可以移动整个对象吗?

标签 swift xcode sprite-kit swift4

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

当我尝试移动生成的对象时,最后一 block 正在移动。如何完全移动形成的形状?

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)

            }
        }
    }

最佳答案

目前尚不清楚您实际上在问什么,大图像和丢失的代码没有帮助。然而,您似乎移动了一个 block :

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

并且您希望将所有 block 移动相同的相对量。您可以通过首先计算每个方向的相对量来代替上面两行来实现这一点:

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

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

 moveAllBlocks(deltaX, deltaY)

此例程需要迭代所有 block ,通过添加增量来更新其位置

HTH

<小时/>

附录

回复评论

I am bad speak english, sorry. example did not solve the problem. Yes, I want to move all the blocks.

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

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

触摸事件告诉您将此图 block 移动到(5, 1)。您当前正在通过分配到图 block 位置来实现移动:

tile.location = (5, 1)

然后面临将其他图 block 移动到哪里的问题,以便它们保持在与您移动的图 block 相同的相对位置。

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

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

现在您有了相对数量(3, -2)来移动图 block ,您可以将所有图 block 移动相同的相对量,它们将彼此保持相同的关系。为此,您需要迭代(循环)所有图 block ,并按 delta 量更改每个图 block 的位置 (3, -2),即添加 3 到行并从列中减去 2

关于swift - 我可以移动整个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48259435/

相关文章:

ios - 从外部项目目录读取 plist 文件

macos - -mouseMoved OSX 不会在 Sprite 套件 SKScene 中被调用

ios - 如何优化以获得更好的帧率?

swift - acceptsFirstMouse ... 不起作用(Swift 4.0,NSView)

xcode - 尝试从查询中将 Parse PFFiles 加载到 UITableView

swift - 使用 Swift 的私有(private) bool 值 : how to set on SKCropNode,?

ios - Firebase Cloud Messaging - 检查现有或可用的主题

ios - 在应用程序中测试本地化字符串时,零和双零代表什么?

ios - Alamofire : How to handle errors globally

ios - 关闭 PopOver ViewController 时黑色闪烁