ios - Sprite-Kit:移动 SKSpriteNode

标签 ios swift sprite-kit

我知道移动一个物体并不难,但我的不同,我尝试了各种方法,但没有一个起作用。

我想要实现什么?

  • 如果用户点击屏幕左侧,球就会向左移动
  • 如果用户点击屏幕右侧,球就会向右移动

所以我直接进入 touchesBegan 并编写了以下内容:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        ball?.removeAllActions()
       for touch in touches {

         let moveBY = SKAction.moveTo(x: touch.location(in: view).x, duration: 1.0)
        self.ball?.run(moveBY)
    } 
}

我尝试了四种不同的方法,我无法克服它,也供你引用,这是我的球的照片 信息:

info

最佳答案

为了将节点移动到您想要的方向,您首先必须知道三件事

  1. 要移动的节点的anchorPoint
  2. 要移动的节点的父节点的 anchorPoint
  3. 要移动的节点的位置

节点的 anchorPoint 属性以从 (0, 0) 到 (1, 1) 的标准化方式存储其值。 SPSpriteNode 默认为 (0.5, 0.5)

节点的 position 属性将其位置存储为正交坐标系中的 (x, y) 坐标,其中点 (0, 0) 位于 parent 是。

因此,场景的 anchorPoint 为 (0.5, 0.5),这意味着如果您将直接子级放置在坐标 (0, 0) 处,则该子级将被定位,使其 anchorPoint 位于 (0, 0),它将始终与其父级的 anchorPoint 匹配。

当您在SKSceneSKNodes内使用这些重载touchesBegan、touchesMoved等时,如果您想获取表示的触摸位置场景(sknode)的所有直接子节点所在的坐标系,您应该执行类似的操作

class GameScene: SKScene {

    override func didMove(to view: SKView) {
        super.didMove(to: view)
        let rect = SKSpriteNode(color: .green, size: CGSize(width: 100, height: 100))
        addChild(rect)
        rect.name = "rect"

        // don't pay attention to these two i need them because i dont have .sks file
        size = CGSize(width: 1334, height: 750)
        anchorPoint = CGPoint(x: 0.5, y: 0.5)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let moveAction = SKAction.move(to: touch.location(in: self), duration: 1)
        childNode(withName: "rect")?.run(moveAction)
    }
}

希望它对您有帮助,您可能遇到的其他问题是您的球不是场景的直接子级,并且您得到的坐标错误

关于ios - Sprite-Kit:移动 SKSpriteNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927884/

相关文章:

ios - 在 ViewController 之外显示 UIAlertController

ios - WKWebView 函数用于检测 URL 是否已更改

ios - 在 previewLayer : AVCaptureVideoPreviewLayer 上绘图

swift - Swift 中的 Sprite Kit Child of Child of Child

swift - 如何在 2 个 skscenes 之间转换

ios - 更新模型层时 CABasicAnimation 无法正确设置动画

ios - AppDelegate 中对成员 'subscript' 的引用不明确

Swift 客户端和根 SSL 证书身份验证

swift - 错误 : Cannot subscript a value of type 'X' with . ..'

swift - 如何将 Sprite 作为类添加到场景中?